例如,在以下代码中:
class Animal
class Dog extends Animal
trait Base {
def a: Animal = new Dog
}
trait Deri extends Base {
override val a: Dog
}
出现以下错误:
error: overriding value a in trait Deri of type Dog; method a in trait Base of type => Animal needs to be a stable, immutable value; (Note that value a in trait Deri of type Dog is abstract, and is therefore overridden by concrete method a in trait Base of type => Animal)
我想知道,因为我已经用 override
显式修改了 Deri
中的 a
,而 Scala 是否选择相反的方式(如错误消息中所示,用 Base
中的内容覆盖 Deri
中的 a
)?
最佳答案
根据Scala Spec ,具体的定义总是覆盖抽象的定义。
This definition also determines the overriding relationships between matching members of a class C and its parents. First, a concrete definition always overrides an abstract definition. Second, for definitions M and M' which are both concrete or both abstract, M overrides M′ if M appears in a class that precedes (in the linearization of C) the class in which M′ is defined.
因此,要使其编译,您必须确保抽象方法可以被具体方法覆盖。更改德里:
trait Deri extends Base { override def a:Animal }
或更改基础
trait Base { val a: Dog = new Dog }
关于scala - 为什么在 scala 中不能用抽象成员覆盖具体成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40172423/