Scala 线性化规则和 super 操作
如果一个类有多个父类,且父类的有相同的函数 f,在子类和父类中调用 super.f 都是按从右到左的调用函数的顺序。
这个规则名为:Linearization Rules
如下的代码
trait Base1 {
def print() { println("Base1") }
}
trait A extends Base1 {
override def print() { println("A"); super.print() }
}
trait B extends Base1 {
override def print() { println("B"); super.print() }
}
class Base2 {
def print() { println("Base2") }
}
trait Base3 {
def print() { println("Base3") }
}
class C extends Base2 with Base3 with A with B {
override def print() { println("C"); super.print() }
}
object Main extends App {
(new C).print()
}
继承顺序为 C -> Base2, Base3, Base1, A, B,输出结果为:
C B A Base1
如果 class C 变成:
class C extends Base2 with A with Base3 with B {
override def print() { println("C"); super.print() }
}
继承顺序为 C -> Base2, Base1, A, Base3, B,输出结果为:
C B Base3