Scala multiple inheritance. Mixin order v.s. Super order.


Code is everything:

trait Base1 {
  println("mixing Base1")

  def print() {
    println("Base1")
  }
}

trait A extends Base1 {
  println("mixing A")

  override def print() {
    println("A")
    super.print()
  }
}

trait B extends Base1 {
  println("mixing B")

  override def print() {
    println("B")
    super.print()
  }
}

class Base2 {
  println("mixing Base2")

  def print() {
    println("Base2")
  }
}

/**
  * C extends Base2 with A with B
  * => inheritance linearization
  * step 1: expansion
  * C extends Base2 with Base1 with A with Base1 with B
  * step 2: duplication removal
  * C extends Base2 with Base1 with A with B
  *
  * So the mixin order is:
  * Base2 -> Base1 -> A -> B
  *
  * Super order is:
  * B -> A -> Base1 (because Base1 mixes in after Base2, so it overrides it)
  **/
class C extends Base2 with A with B {
  println("creating C")

  override def print() {
    println("C")
    super.print()
  }
}

object Main extends App {
  (new C).print()
  /*
  Output:

mixing Base2
mixing Base1
mixing A
mixing B
creating C
C
B
A
Base1
    */
}

 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com