爲什麼x.func
下方回報"B extends B extends B"
? 如何安排此代碼以便返回"B extends A extends Base"
?行爲鏈斯卡拉超級性狀
trait Base {
def name = "Base"
def func = name
}
trait A extends Base {
override def name = "A"
override def func = name + " extends " + super.func
}
trait B extends Base {
override def name = "B"
override def func = name + " extends " + super.func
}
val x = new Base with A with B
println(x.func)
更新:一種安排可能如下。它現在在A
和B
中具有相同的定義func1
。如果我嘗試將其移動到Derived
類別,則不起作用。任何想法如何刪除重複的func1
?
trait Base {
def name = "Base"
def func1(s: String) = s
}
trait Derived extends Base {
def func = func1(name)
}
trait A extends Derived {
override def func1(s: String) = s + " extends " + super.func1(super.name)
override def name = "A"
}
trait B extends Derived {
override def func1(s: String) = s + " extends " + super.func1(super.name)
override def name = "B"
}
val x = new Base with A with B
println(x.func)
一些更多的澄清:在真實場景中的名字是不能FUNC內聯一個獨立的方法。另外,我正在試驗以查看func的定義是否可以在所有擴展Base的特徵中完全相同。 –