加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 为什么“抽象覆盖”不需要在“副本”中“覆盖”?

发布时间:2020-12-16 09:38:48 所属栏目:安全 来源:网络整理
导读:我阅读了Scala中的 section编程,其中引入了抽象覆盖,但是我仍然被这些修饰符的加入所表示的确切困惑。使用这些修饰符的代码片段粘贴在下面: trait Doubling extends IntQueue { abstract override def put(x: Int) { super.put(2 * x) }} 特别是在这种情
我阅读了Scala中的 section编程,其中引入了抽象覆盖,但是我仍然被这些修饰符的加入所表示的确切困惑。使用这些修饰符的代码片段粘贴在下面:

trait Doubling extends IntQueue {
    abstract override def put(x: Int) { super.put(2 * x) }
}

特别是在这种情况下,我对抽象的目的感到困惑,为什么我们无法通过override关键字实现预期的结果。如果我们没有打电话给超级,我们需要关键字抽象吗?为什么或者为什么不?我正在寻找这个关键字组合的详细解释,因为它涉及可堆叠特征。

解决方法

原因是基类方法是抽象的

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) }

这是方程的“另一面”:如果方法确实有实现,那么没有必要将trait的方法标记为抽象:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读