我一直在处理复杂的编译时反射,并发现需要手动使用AST手工编写Scala代码。在进行实验时,我注意到一个奇怪的编译错误,对我来说没有什么意义,所以我尝试在一个测试项目中复制它。
我使用Scala2.10.4。
下面是代码:
Macro.scala:
object Macro {
def reifyTestImpl(c: Context): c.Expr[OffsetDateTime] = {
import c.universe._
val expression = reify(OffsetDateTime.now())
c.echo(c.enclosingPosition, "With reify: " + show(expression.tree))
c.echo(c.enclosingPosition, "With reify (raw): " + showRaw(expression.tree))
expression
}
def manualAstTestImpl(c: Context): c.Expr[OffsetDateTime] = {
import c.universe._
val odtSymbol = typeOf[OffsetDateTime].typeSymbol
val now = newTermName("now")
val expression = c.Expr(
Apply(
Select(Ident(odtSymbol), now),
List()
)
)
c.echo(c.enclosingPosition, "Manual: " + show(expression.tree))
c.echo(c.enclosingPosition, "Manual (raw): " + showRaw(expression.tree))
expression
}
def reifyTest = macro reifyTestImpl
def manualAstTest = macro manualAstTestImpl
}Tester.scala:
object Tester {
def main(args: Array[String]): Unit = {
println(Macro.reifyTest)
println(Macro.manualAstTest)
}
}c.echo的输出是:
With reify: OffsetDateTime.now()
With reify (raw): Apply(Select(Ident(java.time.OffsetDateTime), newTermName("now")), List())
Manual: OffsetDateTime.now()
Manual (raw): Apply(Select(Ident(java.time.OffsetDateTime), newTermName("now")), List())在调用value now is not a member of java.time.OffsetDateTime时,我得到的编译错误是Macro.manualAstTest。
正如回声的输出所示,这两个表达式是相同的--但是一个表达式工作(来自reify的表达式),而另一个表达式不工作(使用apply-select构建的表达式)。
两者之间有什么区别呢?
发布于 2017-03-15 22:37:03
找到罪魁祸首。
显然,typeOf[OffsetDateTime].typeSymbol返回符号就像从Scala类返回的那样,也就是说,没有它的静态成员。
添加.companionSymbol似乎像从Scala对象返回的那样返回符号,也就是说,只有静态成员(顾名思义.)
因此,以下更改使其工作:
val odtSymbol = typeOf[OffsetDateTime].typeSymbol.companionSymbolhttps://stackoverflow.com/questions/42820935
复制相似问题