【发布时间】:2014-02-24 06:49:36
【问题描述】:
我想编写一个返回类型取决于参数的宏。简化示例:
def fun[T](methodName: String) = macro funImpl[T]
def funImpl[T: WeakTypeTag](c: Context)(methodName: c.Expr[String]): /* c.Expr[T => return type of T.methodName] */ = {
// return x => x.methodName
}
显然funImpl 的注释掉返回类型是非法的。我试过简单地返回一个Tree,但这会产生一个错误:
[error] macro implementation has wrong shape:
[error] required: (c: scala.reflect.macros.Context): c.Expr[Any]
[error] found : (context: scala.reflect.macros.Context): context.Tree
[error] type mismatch for return type: c.universe.Tree does not conform to c.Expr[Any]
[error] def fun[T] = macro PrivateMethodMacro.funImpl[T]
[error] ^
可以写这样的宏吗?显然,如果返回类型作为另一个类型参数传递,就像Is it possible to write a scala macro whose returntype depends on argument? 的答案一样,但这不是我想要的。
【问题讨论】:
标签: scala scala-macros