scala类型系统:10) 交集类型与联合类型

《快学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之后再介绍。

4 thoughts on “scala类型系统:10) 交集类型与联合类型

  1. Pingback: scala类型系统:柯里-霍华德同构 | 在路上

  2. Scala for the Impatient没看过,不过intersection type(交集类型)跟with关键字(继承)没有关系,A extends B with C with D意味着A能有B、C和D定义的任何成员,B、C和D之间存在重名的需要一定的重载处理。

Leave a Reply

Your email address will not be published. Required fields are marked *