Is it possible to generate Apply from WeakTypeTag inside a scala macro?

前端 未结 1 421
无人及你
无人及你 2021-01-19 05:44

I have a WeakTypeTag of some type in my macro, and I want to generate code as follows:

macroCreate[SomeObject] // => SomeObject(1)

相关标签:
1条回答
  • 2021-01-19 06:01

    You can get the symbol of the companion object and then use the universe's Ident(sym: Symbol): Ident factory method:

    def macroCreate[A] = macro _macroCreate[A]
    
    def _macroCreate[A](c: Context)(implicit wtt: c.WeakTypeTag[A]) = {
      import c.universe._
    
      c.Expr(
        Apply(
          Select(Ident(wtt.tpe.typeSymbol.companionSymbol), newTermName("apply")),
          c.literal(1).tree :: Nil
        )
      )
    }
    

    And then:

    scala> case class SomeObject(i: Int)
    defined class SomeObject
    
    scala> macroCreate[SomeObject]
    res0: SomeObject = SomeObject(1)
    
    scala> macroCreate[List[Int]]
    res1: List[Int] = List(1)
    

    If you really mean that SomeObject is the type of the object (i.e., not the type of its companion class), just remove the .companionSymbol above.

    0 讨论(0)
提交回复
热议问题