scala - 为什么在 scala 中不能用抽象成员覆盖具体成员?

标签 scala oop overriding

例如,在以下代码中:

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/

相关文章:

java - 在 OS X 上 Play Framework 运行时错误

scala - 如何在单个路由中解码 POST 参数和 JSON 正文?

scala - Play 2 Scala 使用多个枚举器提供 Websocket 输出 Iteratee(PatchPannel?)

javascript - prototype.constructor 和内置 Object() 有什么区别

perl - 将SUPER引用到对象的父类(super class)

java - 如何在 Scala 中将复杂的 JSON 字符串转换为 MAP

oop - 我可以(应该)继承 R 中函数的一部分吗?

ios - 如何覆盖包含 block 的objC中的方法?

javascript - 我们可以在 Magento 中覆盖核心 js 文件吗?

html - 如何覆盖设置文件基础