class Root{ def hello(){ println("Hello,Root!") } } class SubA extends Root{ override def hello() { println("Hello,SubA!") } } trait D extends Root{ def traitHello(){ super.hello(); } }
对于trait D而言,虽然其扩展了class Root,但是super.hello()并不是指Root的hello方法 ,而是在D被混入后的目标类的hello.
SCALA编译原文描述不严格:
The Doubling trait has two funny things going on. The first is that it declaresa superclass, IntQueue. This declaration means that the trait can only bemixed into a class that also extends IntQueue. Thus, you can mix Doublinginto BasicIntQueue, but not into Rational.
因为原文中IntQueue是抽象类,所以无法展示Doubling对IntQueue的super调用,我们这里的这个例子,Root不是抽象类,本身也可以直接混入D,而不仅仅是只有子类才可以混入。
val e = new Root with D
e.traitHello()
val f = new SubA with D
f.traitHello()
输出:
Hello,Root!
Hello,SubA!