scalashapelessscala-3singleton-type

In Scala 3, how to summon a constant from its type?


assuming that I want to summon a constant 3 from its type 3.

In Scala 2, this can be easily done with shapeless Witness:

val w = implicitly[Witness[3]]
w.value

this has no counterpart in Scala 3, I've tried the following:

  val v2 = summon[3]

  val v3 = inline constValue[3]

and none of them appears to be working. What's the canonical way to implement this? And what can be done to make it cross-compilable between Scala 3 & 2.13?


Solution

  • In Scala 3 use scala.compiletime.constValue (documented here)

    constValue[3]
    

    or good old Scala 2 type class scala.ValueOf

    valueOf[3]  // from scala.runtime.stdLibPatches.Predef
    

    https://scastie.scala-lang.org/DmytroMitin/puPRyLUgQmaVfXslE7Di7Q/8

    implicitly[ValueOf[3]].value should be cross-compilable between Scala 3 & 2.13 as long as implicitly exists in Scala 3.

    summon[3] can't be correct because 3 is not an implicit.