Scala类型 6:复合类型 & with关键字

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") }

转载于:https://my.oschina.net/sean1984/blog/390994

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值