Home > OS >  Scala 3 Macro - Retain a generic type in runtime
Scala 3 Macro - Retain a generic type in runtime

Time:10-01

I'm looking for an option to retain a generic type in runtime in Scala3. In Scala2 there was a TypeTag for this, however, now it is removed and the suggested option is to use macros (https://contributors.scala-lang.org/t/scala-3-and-reflection/3627).

The documentation, however, is somewhat cryptic...

This is what I'm trying to do:

Here's a macro implementation:

object TestMacroImpl {
  def getClassImpl[T](using Quotes)(using t: Type[T]): Expr[Class[T]] = '{
    classOf[${t}]
  }
}

Here's a macro:

import macros.TestMacro.getClassMacro

class TypedBox[T] {
  val staticClass: Class[T] = TypedBox.getStaticClass[T]
}

object TypedBox {
  inline def getStaticClass[T] = ${ getClassMacro[T] }
}

Test:

object Test {
  def main(args: Array[String]): Unit = {
    val stringBox = TypedBox[String]()
    println(stringBox.staticClass)
  }
}

I would envision this to be resolved as val staticClass = classOf[String]

But this does not compile, I'm getting:

/workspace/macros-test/src/main/scala/macros/TestMacro.scala:7:13
t.Underlying is not a class type
    classOf[${t}]

What am I missing?

CodePudding user response:

Not really sure why but I don't think you can reliably get an Expr[Class[T]] out of macros (from what I understood, it could be that the Class does not yet exist at the time of macro execution).

Plus, a Class[T] does not retain the parameterized types: classOf[Map [String, String]] = classOf[Map[Int, Int]] for instance.

If you don't care about them, I'd use a ClassTag instead of TypeTag which is still available in Scala 3. And no need for macros.

By the way, in macros, you can write something like the following to get a Expr[ClassTag[T]]:

private def getClassTag[T](using Type[T], Quotes): Expr[ClassTag[T]] = {
    import quotes.reflect._

    Expr.summon[ClassTag[T]] match {
      case Some(ct) =>
        ct
      case None =>
        report.error(
          s"Unable to find a ClassTag for type ${Type.show[T]}",
          Position.ofMacroExpansion
        )
        throw new Exception("Error when applying macro")
    }

  }

Finally, you might find some useful things at https://github.com/gaeljw/typetrees/blob/main/src/main/scala/io/github/gaeljw/typetrees/TypeTreeTagMacros.scala#L8 (disclaimer: I wrote it for personal projects).

  • Related