以下兩者有什麼區別?關於性狀的問題
1#
trait B extends A {
}
2#
trait B { self: A =>
}
其中A
是一個抽象類。
> >編輯:
請相對於可插拔飛行和嘎嘎叫的行爲解釋的Duck
S上下面的例子:
abstract class Duck {
def fly(): Unit
def quack(): Unit
def swim() {
println("Woodoowoodoowoodoo...")
}
}
trait FlyingWithWings extends Duck {
override def fly() {
println("Me can fliez! :D")
}
}
trait FlyingNoWay { self: Duck =>
def fly() {
println("Me cannot fliez! :(")
}
}
trait Quack extends Duck {
override def quack() {
println("Quack! Quack!")
}
}
trait MuteQuack { self: Duck =>
def quack() {
println("<<Silence>>")
}
}
class MallardDuck extends Duck with FlyingWithWings with MuteQuack
object Main {
def main(args: Array[String]) {
val duck = new MallardDuck
duck.fly()
duck.quack()
}
}
輸出:
我可以fliez! :d
< <沉默>>
查看http://stackoverflow.com/questions/2224932/difference-between-trait-inheritance-and-self-type-annotation的副本,本身是http://stackoverflow.com/questions/1990948的副本/什麼是差別之間的自我類型和特質子類 – VonC 2010-07-02 07:03:23