, , : , c.Expr[Any], .
, - , , , - , 2.11 whitebox blackbox, , , ( ).
, , ( quasiquotes macro paradise plugin 2.10, ):
import scala.language.experimental.macros
import scala.reflect.macros.Context
def funImpl[T: c.WeakTypeTag](c: Context)(
method: c.Expr[String]
): c.Expr[Any] = {
import c.universe._
val T = weakTypeOf[T]
val methodName: TermName = method.tree match {
case Literal(Constant(s: String)) => newTermName(s)
case _ => c.abort(c.enclosingPosition, "Must provide a string literal.")
}
c.Expr(q"(t: $T) => t.$methodName")
}
def fun[T](method: String) = macro funImpl[T]
:
scala> fun[String]("length")
res0: String => Int = <function1>
, - , , Any. (, , ) funImpl c.Expr[T => Any] - c.Expr[T => Any](q"_.$methodName"), , , - , .