《快学scala》这本书(即《Scala for the Impatient》中文版)在介绍复合类型时提到它们也被成为“交集类型”,跟老高确认了一下,这块的英文原文是:
In order to belong to the compound type, a value must belong to all of the individual types. Therefore, such a type is also called an intersection type.
我之前以为是union type
还觉得他翻译的别扭,是我理解错了。他翻译的是合适的,intersection type
交集类型:
X with Y with Z
scala是通过with
关键字来支持这种形式的。
而 union type
是“或”的意思
X or Y or Z
在scala里并没有在语言级别支持 union type,但可以通过一些技巧实现。在stackoverflow上看到有2种实现技巧。
第一种方法,通过隐式转换(上下文界定):
class StringOrInt[T]
object StringOrInt {
implicit object IntWitness extends StringOrInt[Int]
implicit object StringWitness extends StringOrInt[String]
}
object Bar {
def foo[T: StringOrInt](x: T) = x match {
case _: String => println("str")
case _: Int => println("int")
}
}
第二种方式:Curry-Howard isomorphism(柯里-霍华德同构),这个有点复杂,等type lambda
之后再介绍。
Pingback引用通告: scala类型系统:柯里-霍华德同构 | 在路上
Scala for the Impatient没看过,不过intersection type(交集类型)跟with关键字(继承)没有关系,A extends B with C with D意味着A能有B、C和D定义的任何成员,B、C和D之间存在重名的需要一定的重载处理。
我觉得这里面的intersection type指的是类型的交际,例如A with B with C 类型的对象是A、B、C三种类型的对象集合的交集,
你说的对