似乎无法通过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
满足特质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
(a: AImpl).foo()
的任何调用都作为宏在使用时进行扩展,还是只需要生成(普通)foo()
方法的内容? - gourlaysama