trait 可以类似于抽象类,域和方法可以有定义,也可以抽象
trait 一般表示单一的功能,
当引用多个trait时,如果存在相同的值或者方法,需要人为解决冲突,
冲突问题
trait A {
var x =13;
def f = x+12
}
trait B {
def x =14;
def f =x*12
val c =123
}
class C extends A with B {
}
object EnumerationColor {
def main(args: Array[String]): Unit = {
println( new C().x)
println( new C().f)
}
}
Error:(20, 7) class C inherits conflicting members:
variable x in trait A of type Int and
method x in trait B of type => Int
(Note: this can be resolved by declaring an override in class C.);
other members with override errors are: f
class C extends A with B {
解决冲突方法 。重写
trait A {
var x =13;
def f = x+12
val c = 23
}
trait B {
def x =14;
def f =x*12
val c =123
}
class C extends A with B {
override val x= super[A].x +super[B].x+ c
override val f= super[B].f
override val c: Int = 12
}
object EnumerationColor {
def main(args: Array[String]): Unit = {
println( new C().x)
println( new C().f)
}
}
注意一下:super[A] 只能用于方法,不能用于域。也就是只能用def定义的才能用