复合类型与with关键字

符合类型的表现形式为:

class A extends B with C with D with E 

应做类似如下形式解读:

class A extends (B with C with D with E)

这正是《scala for the impatient》这本书上的内容,我下面的理解也基本源于这本书。

T1 with T2 with T3 …

这种形式的类型称为复合类型(compound type)或者也叫交集类型(intersection type)。

跟结构类型类似,可以在一个方法里声明类型参数时使用复合类型:

scala> trait X1; trait X2;

scala> def test(x: X1 with X2) = {println("ok")}
test: (x: X1 with X2)Unit

scala> test(new X1 with X2)
ok

scala> object A extends X1 with X2

scala> test(A)
ok

也可以通过 type 声明:

scala> type X = X1 with X2
defined type alias X

scala> def test(x:X) = println("OK")
test: (x: X)Unit

scala> class A extends X1 with X2

scala> val a = new A

scala> test(a)
OK

在上一篇介绍结构类型时也提到过复合类型中也可包含结构类型:

scala> type X = X1 with X2 { def close():Unit }
defined type alias X



你可能感兴趣的:(scala)