您的位置:首页 > 其它

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

2016-11-09 09:51 375 查看

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

转载自:http://hongjiang.info/scala/   推荐大家阅读下这位大哥出版的书《Scala函数式编程》
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: