我读了section在 Scala 编程中,引入了抽象重写,但我仍然对这些修饰符的连接到底意味着什么感到困惑。使用这些修饰符的代码片段粘贴在下面:
trait Doubling extends IntQueue {
abstract override def put(x: Int) { super.put(2 * x) }
}
特别是,我对这种情况下 abstract
的用途感到困惑,以及为什么我们不能仅使用 override
关键字来实现预期结果。如果我们没有包含对 super
的调用,我们是否需要关键字 abstract
?为什么或者为什么不?我正在寻找此关键字组合的详细解释,因为它与可堆叠特征有关。
最佳答案
原因是基类方法是抽象
abstract class IntQueue {
def get(): Int
def put(x: Int)
}
如果您不将摘要
放在特征上,您最终会得到您正在寻求的解释:
trait Doubling extends IntQueue {
override def put(x: Int) { super.put(2 * x) }
}
<console>:9: error: method put in class IntQueue is accessed from
super. It may not be abstract unless it is overridden by a member
declared `abstract' and `override'
override def put(x: Int) { super.put(2 * x) }
所以 - 您需要将该方法标记为abstract
。
这是等式的“另一面”:如果方法确实有实现,则无需将 trait
的方法标记为 abstract
:
abstract class IntQueue {
import collection.mutable._
val q = Queue[Int]()
def get(): Int = { q.dequeue() }
def put(x: Int) = { q.enqueue(x) }
}
现在不需要包含摘要
trait Doubling extends IntQueue {
/* Look Ma! no abstract here ! */ override def put(x: Int) { super.put(2 * x) }
}
defined trait Doubling
关于scala - 为什么子特征中需要 "abstract override"而不是单独的 "override"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23645172/