Jas*_*son 3 inheritance scala traits
假设我创建了一个混合在两个特征中的类,这两个特征都实现了一个通用方法,例如:
abstract class Base {
var x:Int
def adder:Int
}
trait One extends Base {
def adder() = {x+=2; x}
}
trait Two extends Base {
def adder() = {x+=3; x}
}
class WhichOne(var x:Int = 10) extends Base with One with Two
println((new WhichOne()).adder())
Run Code Online (Sandbox Code Playgroud)
在运行时,Scala当然抱怨,因为它不知道更喜欢哪个特性:
$ scala MixUpTraitImplems.scala
MixUpTraitImplems.scala:18: error: class WhichOne inherits conflicting members:
method adder in trait One of type ()Int and
method adder in trait Two of type ()Int
(Note: this can be resolved by declaring an override in class WhichOne.)
class WhichOne(val x:Int = 10) extends Base with One with Two
^
Run Code Online (Sandbox Code Playgroud)
当然,重写adder()意味着我继续执行新版本adder,但如果我不想要那个呢?如果我想使用addertrait 中显式包含的实现One或者Two怎么办?