使用 Scala 宏我想访问函数 f 的源代码。
这是我的问题的简化示例:
def logFImplementation(f: => Boolean) {
val sourceCodeOfF: String = ... // <-- how to get source code of f??
println("Scala source of f=" + sourceCodeOfF)
}
so for:
logFImplementation { val i = 5; List(1, 2, 3); true }
它应该打印:
Scala source of f=val i: Int = 5; immutable.this.List.apply[Int](1, 2, 3); true
(现在我测试了用于在运行时访问源代码文本的宏 https://stackoverflow.com/questions/15972419/macro-to-access-source-code-text-at-runtime它非常适合{ val i = 5; List(1, 2, 3); true }.logValueImpl
但对于f.logValueImpl
它只是打印f
.)
感谢您的任何建议。
这可能是“线程死灵术”,因为这个问题已经很老了。我不得不努力解决这个问题。
import scala.reflect.macros.blackbox.Context
import scala.language.experimental.macros
object FunctionWrapper {
implicit def apply[P, R](fn: P => R): FunctionWrapper[P, R] = macro apply_impl[P, R]
def apply_impl[P: c.WeakTypeTag, R: c.WeakTypeTag](c: Context)(fn: c.Expr[P => R]):
c.Expr[FunctionWrapper[P, R]] = {
import c.universe._
c.Expr(q" new FunctionWrapper($fn, ${show(fn.tree))})")
}
}
class FunctionWrapper[P, R](val fn: P => R, description: String)
extends Function1[P, R] {
def apply(p: P) = fn(p)
override def toString = description
}
它的使用示例(必须位于单独的编译模块中)是:
object FunctionWrapperUser {
def main(args: Array[String]): Unit = {
val double = FunctionWrapper((i: Int) => i * 2)
println(s"double to String is $double")
println(double(4))
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)