Obtaining the name of a type (Scala 3)

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

1 Like

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]"
2 Likes

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

1 Like

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.

1 Like

Yep. Most probably changes on nightly.

Works perfectly, thanks @hmf and @Jasper-M !

For anyone who arrives here in 2023, it looks like QuoteContext is now just Quotes, and that .show on summon[Type[A]] doesn’t exist anymore (Type.show[A] however does).

Also, make sure not to define the call to the macro method in the same source, although the error message is quite explicit about that.

I got this working for Scala 3.3.0.

Hope this helps!

2 Likes