假设我创建了一个类,混合了两个 trait,这两个 trait 都实现了一个共同的方法,例如下面所示:
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())
在运行时,Scala当然会抱怨,因为它不知道应该选择哪个trait:
$ 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
^
当然,覆盖 adder()
意味着我要实现一个新版本的 adder
,但是如果我不想这样做怎么办?如果我想明确使用 trait One
或 Two
中显式包含的 adder
实现呢?
adder
方法上添加override
关键字,则将选择最后一个实现(从左到右)。在这种情况下,是Two
。但是依赖于声明顺序并不是一个好的设计。 - jpmelanson