我想编写一个宏,其中返回类型取决于参数。简单示例:宏返回类型取决于参数
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?的回答中一样,但这不是我想要的。
在2.11中,'警告:宏定义必须明确指定返回类型(推断任何来自宏的impl的c.Expr [Any]已被弃用,并将在2.12中停止工作)' –
您是否正在使用上下文'白盒'套餐? –
当然。未分化的上下文更被弃用。 –