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.
val e = new Root with D
e.traitHello()
val f = new SubA with D
f.traitHello()
输出:
Hello,Root!
Hello,SubA!
本文探讨Scala中特质与类之间的交互方式,特别是在super调用上下文中的行为。通过具体示例说明了当特质混合到类中时,super关键字如何引用目标类而非基类的方法。
66

被折叠的 条评论
为什么被折叠?



