在第一种情况下,new Base with One with Two {} foo
(这与new One with Two {} foo
),“特质堆栈”非常明显。这Two
has a foo
这称为foo
其超级(One
)这称为foo
其超级(Base
).
在第二种情况下,new Foo with One with Two {} bar
(这与new One with Two {} bar
),“特征堆栈”是 Base->Foo->One->Two。你打电话bar
but Two
has no bar
and One
has no bar
. Foo
has a bar
这称为foo
其超级(Base
).
UPDATE
考虑一下 @Dima 提议的这个 mod。
trait Base { def foo = "Base" }
trait Foo extends Base { def bar = foo + " <: " + super.foo }
trait One extends Foo { override def bar = super.bar
override def foo = "One" }
trait Two extends Foo { override def bar = super.bar
override def foo = "Two" }
new One with Two {} bar // no Base or Foo needed
是的,这给出了与之前相同的输出:res0: String = Two <: Base
Now Two
称为bar
其超级(One
)这称为bar
其超级(Foo
)这称为foo
(not bar
)其超级。
所有这些bar
活动与foo
定义。Two
从不调用foo
其超级所以One.foo
从未使用过,也不能成为输出的一部分。
不同的方法
考虑以下。
trait B { def id = "B" } // B for Base
trait V extends B { override def id = "V" }
trait W extends B { override def id = "W" }
trait X extends B { override def id = "X" }
trait Y extends B { override def id = "Y" }
trait Z extends B { override def id = "Z" }
trait R extends B { override def id = "R"; def mySup = super.id } // Required
现在尝试以多种不同的方式实例化它。
val r = new V with Y with W with R with X {} // B not needed
// or
val r = new W with R with Z with X with V {}
// or
val r = new R with Y with V with B with W {}
// or
val r = new Z with Y with X with W with R {}
// etc.
在每种情况下r.id
将是链中的最后一个特征并且r.mySup
将是出现在R
(or B
如果之前没有指定任何内容R
).