Generic number literals extension

Would it be possible to implement support of generic number literals in extension methods?

import scala.util.FromDigits
import scala.math.BigDecimal
class CustomNumber(val v:BigDecimal)
object Test{
  given BDC as FromDigits[CustomNumber] {
     def fromDigits(digits: String): CustomNumber = {
  def (value: CustomNumber) cne: CustomNumber = value
  def cn(value: CustomNumber): CustomNumber = value
  @main def run():Unit = {
    val v:CustomNumber = 10 //ok
    println(cn(10)) //ok
    println(10.cne)  //Dotty 0.18.1-RC1r says: value cne is not a member of Int - did you mean Int(10).+?

IMHO: It will be just great.

I strongly support this request, as it would be useful for me as well. One way to do it would be to encode numeric literals as some hidden type h with an implicit conversion from h to the expected type. Would that be feasible ?

10.cne would need both extension method and wrapping to happen at the same time. Scala compiler doesn’t look for more than one conversion/ extension of a type at once, otherwise compilation times could be even longer than today. You can however split that mechanics into two steps: first force wrapping by ascribing type and then select cne extension method:

(10: CustomNumber).cne

That does work under Dotty.

1 Like

At the last SIP meeting, it looked like there will not be sufficient support for generic number literals. So it’s likely they will not make it into 3.0. They are not off the table – I do hope that we can add them in a later version.

1 Like

This seems like another way to make Scala more complex than it needs to be. People will wonder why some number suffixes require a dot but some don’t, or why are some are case sensitive and some aren’t. We already have string literals which are very close to the same number of characters, and are more flexible.

It needs in cases when they provide custom numeric types and broadly use them. Could you imagine how comfortable to use string interpolation to create all number constants, actually it is not very comfortable at least for me.
It can be said it is rare case, but it can be also said it is survivorship bias.

I think that is not the problem as it can readily make an implicit conversion followed by an extension:

import scala.language.implicitConversions
given Conversion[Int, CustomNumber] = x => CustomNumber(BigDecimal.valueOf(x))
println(10.cne) // ok