【问题标题】:Scala traits mixin order and super callScala 特征混合顺序和超级调用
【发布时间】:2014-12-19 16:17:58
【问题描述】:

我有这个代码:

trait base{
  def msg: Unit= {
    println{"base"}
  }
}

trait foo extends base {
  abstract override def msg: Unit ={
    super.msg
    println("foo")
  }
}

class base2{
  def msg:Unit = {
    println{"base 2"}
  }
}

class test extends base2 with foo{
   override def msg: Unit ={
    super.msg
    println("done")
  }
}

如果我打电话给(new test).msg,则会打印出如下内容:base, foo, done

但是,如果我将基本特征更改为:

trait base{
  def msg: Unit
}

它会打印出如下内容:base 2, foo, done

我知道with 的顺序是从右到左(最后一个在前)但是extends 怎么样?为什么有时会打印base2,但有时会打印base

【问题讨论】:

  • 这种怪异是我避免蛋糕图案的原因。
  • 如果它像在 Groovy 中一样工作,那么您需要将 super.msg 添加到 base 特征,以便它链接到您的 base2 类。没有在base 中实现,base2 通过foosuper.msg 调用。

标签: scala mixins traits linearization


【解决方案1】:

当您省略实现时,base特征的模板,并具有不同的评估规则。见Scala specification

【讨论】:

  • 不错! --------> +1
【解决方案2】:

Scala 有一种叫做类型线性化的东西。它定义了初始化顺序。阅读这里http://eed3si9n.com/constraining-class-linearization-in-Scala

【讨论】:

    猜你喜欢
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 2011-04-13
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2012-05-09
    相关资源
    最近更新 更多