以下代码无法使用 Scala 2 编译(测试 2.13.7 和 Scala 2.12.15):
trait AttributeBase
trait Attribute extends AttributeBase {
def name: String
}
trait Base {
def attribute: AttributeBase
}
trait Derived { self: Base =>
def attribute: Attribute
def name = attribute.name
}
该代码可以使用 Scala 3 编译。使用 Scala 2 的错误是:
值名称不是 AttributeBase 的成员
extends
当使用而不是 self 类型时,它编译得很好:
trait Derived extends Base {
另一种可能的解决方法是:
def name = (this:Derived).attribute.name
为什么Derived.attributed
假定的类型是AttributeBase
而不是Attribute
?这是 Scala 编译器错误,还是某些 Scala 2 限制?