scalascala-macrosscala-quasiquotesscalameta

How does one use quasiquotes to obtain the type of a value?


I’m trying to write the following:

val value: Int = 3
val tpe = typeOf(value)    // This is pseudocode. What should
                           // actually go on this line?
q"""
type U = $tpe
val v: U = $value
"""

Essentially, I need to capture the type of value (Int) in tpe and assign it to U. How does one do this?


Solution

  • Try

    import scala.reflect.runtime.universe._
    def getType[A: TypeTag](a: A): Type = typeOf[A]
    
    val value: Int = 3
    val tpe = getType(value) // Int
    

    Connected question: How does one obtain the type of the value that an AST represents?