Hello,
What would be a good way to obtain the name of a type in Scala 3?
i.e.
def typeName[A]: String = ???
In Scala 2 I’ve used TypeTag
, but I believe this is not available in Scala 3.
Cheers
Hello,
What would be a good way to obtain the name of a type in Scala 3?
i.e.
def typeName[A]: String = ???
In Scala 2 I’ve used TypeTag
, but I believe this is not available in Scala 3.
Cheers
I don’t think a real TypeTag
equivalent is available out of the box. But there’s izumi-reflect which should provide an alternative to TypeTag
for both Scala 2 and 3. And for simply getting the name it’s not so hard to write something yourself, once you know what you have to write.
import scala.quoted.{Type, Expr, QuoteContext}
def tpeNmeMacro[A: Type](using QuoteContext) = {
val name = Type.show[A]
Expr(name)
}
inline def typeName[A] = ${tpeNmeMacro[A]}
typeName[Option[String]] // "scala.Option[scala.Predef.String]"
I could not get this to compile in 3.0.0-M1. The following seems to work:
def tpeNmeMacro[A](using xt:Type[A], ctx: QuoteContext) = {
import qctx.reflect._
val name = xt.show
Expr(name)
}
inline def typeName[A]: String = ${tpeNmeMacro[A]}
HTHs
Type.show
might be a more recent addition.
Here is another version that is closer to @Jasper-M’s solution:
def tpeNmeMacro[A: Type](using QuoteContext) = {
val name = summon[Type[A]].show
Expr(name)
}
inline def typeName[A]: String = ${tpeNmeMacro[A]}
Tested on 3.0.0-M1. Take heed that the documentation is for the latest M2 nightly. There has been at least one very minor breaking change.
Yep. Most probably changes on nightly.