我正在尝试使用宏注释对类的构造函数值进行注释。假设实现了名为@identity
的宏注释,并在类A的类定义中按以下方式使用它:
class A(@identity val foo: String, // causes error
val bar: String) {
@identity val foobar: String = "" // doesn't cause error
}
仅在注释foobar
时,一切都可以编译。但是,在注释foo
时,出现以下编译时错误:
没有伴侣的顶级类只能扩展为同名类或由同名伴侣组成的块
有人可以详细说明这个错误以及为什么会发生吗?
答案 0 :(得分:2)
我怀疑您调用了宏
import scala.annotation.{StaticAnnotation, compileTimeOnly}
import scala.language.experimental.macros
import scala.reflect.macros.whitebox
@compileTimeOnly("enable macro paradise to expand macro annotations")
class identity extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro identity.impl
}
object identity {
def impl(c: whitebox.Context)(annottees: c.Tree*): c.Tree = {
import c.universe._
println(s"$annottees")
q"..$annottees"
}
}
喜欢
class A(@identity val foo: String,
val bar: String) {
@identity val foobar: String = ""
}
object A
那你有错误
Warning:scalac: List(<paramaccessor> val foo: String = _, class A extends scala.AnyRef {
<paramaccessor> val foo: String = _;
<paramaccessor> val bar: String = _;
def <init>(foo: String, bar: String) = {
super.<init>();
()
};
@new identity() val foobar: String = ""
}, object A extends scala.AnyRef {
def <init>() = {
super.<init>();
()
}
})
Warning:scalac:
Warning:scalac: List(<paramaccessor> val foo: String = _, def <init>(foo: String, bar: String) = {
super.<init>();
()
})
Warning:scalac: List(val foobar: String = "")
Error:(8, 12) top-level class with companion can only expand into a block consisting in eponymous companions
class A(@identity val foo: String,
Error:(8, 12) foo is already defined as value foo
class A(@identity val foo: String,
Error:(8, 12) foo is already defined as value foo
class A(@identity val foo: String,
问题是,您选择一个类(可能还伴随对象),并且不仅返回它们,而且还返回val foo
,因此您更改了禁止的https://docs.scala-lang.org/overviews/macros/annotations.html顶级定义的数量/样式>
顶级扩展必须保留注释者的数量,其样式和名称,唯一的例外是,一个类可能会扩展为同名类以及同名模块,在这种情况下,它们将自动成为按照先前的规则。
例如,如果我们更改宏
def impl(c: whitebox.Context)(annottees: c.Tree*): c.Tree = {
import c.universe._
println(s"$annottees")
q"..${annottees.tail}" // addded tail
}
然后一切都会编译。