Scala traits mixin order and super call

谁都会走 提交于 2019-12-22 04:45:07

问题


I have this code:

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

If I call (new test).msg, this prints out things like: base, foo, done

However, if I change the base trait to:

trait base{
  def msg: Unit
}

it prints out things like: base 2, foo, done

I understand the order of with is from right to left (last one comes first) but how about extends? How come sometimes it prints base2, but sometimes base?


回答1:


When you omit the implementation, base is a template of a trait and has different evaluation rules. See the Scala specification




回答2:


Scala has something called type linearization. It defines initialization order. Read here http://eed3si9n.com/constraining-class-linearization-in-Scala



来源:https://stackoverflow.com/questions/27569901/scala-traits-mixin-order-and-super-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!