with 关键字:
class A extends B with C with D with E
解读方式:
class A extends (B with C with D with E)
(B with C with D with E)首先是一个整体,再由 A 去继承。
注:对于Java中的菱形继承问题;Scala的解决策略是:
1. 继承class混入trait:(extends SuperClass with subClass|subTrait with … ) 必须是一个继承链(左->右)
2. 继承无关的多trait:(class extends T1 with T2 with …), T1和T2中相同字段或方法时,会编译错误-inherits conflicting members…(继承成员冲突)。如:
trait T1 { val a = 1 }trait T2 { val b = 2 }class SubClass extends T1 with T2
编译会报错:Error:(7, 7) class SubClass inherits conflicting members:
复合类型:
T1 with T2 with T3 ...
这种形式的类型-复合类型(compound type),或交集类型(intersection type)。
在方法声明参数类型 时使用复合类型:
def func (x: T1 with T2) = { println("hello") }
func(new T1 with T2)
type声明 复合类型:
type T = X1 with X2
def func (x: T) = { println("hello") }
复合类型中使用结构类型:
def func (x: X1 with X2 { def hello(): Unit }) = { println("hello") }