通过 def 宏实现抽象方法似乎是不可能的:
import scala.reflect.macros.Context
import language.experimental.macros
trait A {
def foo(): Unit
}
object AImpl {
def fooImpl(c: Context)(): c.Expr[Unit] = {
import c.universe._
c.Expr[Unit](reify().tree)
}
}
trait AImpl extends A {
def foo(): Unit = macro AImpl.fooImpl
}
这失败并出现以下错误:
[error] .../A.scala:17: overriding method foo in trait A of type ()Unit;
[error] macro method foo cannot override an abstract method
[error] def foo(): Unit = macro AImpl.fooImpl
[error] ^
如果我删除extends A
它会编译。但显然我想AImpl
满足 trait A
。如何解决这个问题?
另一个尝试:
trait AImpl extends A {
def foo(): Unit = bar()
def bar(): Unit = macro AImpl.fooImpl
}
给出新错误:
[error] macro implementation not found: bar (the most common reason for that is that
you cannot use macro implementations in the same compilation run that defines them)
[error] one error found