【问题标题】:Find actual type of a method parameter in macro在宏中查找方法参数的实际类型
【发布时间】:2014-05-04 04:34:08
【问题描述】:

假设我有一个宏实现

def testImpl[T](c:Context)(implicit wtt:c.WeakTypeTag[T]):c.Tree = {
    import c.universe._

    def info(msg: Any) = c.info(c.enclosingPosition, msg.toString, true)

    val parameter = wtt.tpe.member(TermName("f")).paramLists(0)(0)

    info(parameter.typeSignature)

    q"{}"
}

还有一个宏定义

def test[T]:Unit = macro DerivingImpl.testImpl[T]

此宏在其类型参数中找到函数f,并打印有关其第一个参数类型的信息。

现在如果我像这样使用这个宏

trait Trait[A] {
    def f(x:A): Int
}

test[Trait[Int]]

我得到了A 打印。我想得到Int。我知道调用member 返回的方法符号没有关于具体应用类型的信息。那么,找到参数的实际类型的正确方法是什么?

谢谢。

【问题讨论】:

    标签: scala scala-macros


    【解决方案1】:
    val f = wtt.tpe.member(TermName("f"))
    val MethodType(parameter :: Nil, _) = f.typeSignatureIn(wtt.tpe)
    info(parameter.typeSignature)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-04
      • 2019-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-10
      相关资源
      最近更新 更多