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函数式编程》
相关文章推荐
- Scala类型 10 :交集类型(intersection type)与联合类型(union type)
- Scala in depth 6 Scala的类型系统 上
- Scala in depth 6 Scala的类型系统 下
- scala类型系统:11) upper bounds & lower bounds
- Scala 类型系统实战之编程进阶(4)
- Scala 容器与类型系统之编程进阶(3)
- SQL 10 函数 3 日期时间函数 - 2 主流数据库系统中日期时间类型的表示方式
- 第四课 Scala模式匹配、类型系统彻底精通与Spark源码阅读
- scala类型系统:13) context bounds
- scala类型系统:19) Manifest与TypeTag
- 第4讲:Scala模式匹配和类型系统
- Scala模式匹配和类型系统
- 第4集:Scala模式匹配、类型系统彻底精通与Spark源码阅读
- scala类型系统:12) view bounds
- 【Scala类型系统】函数式Queue的简易实现
- Scala in depth 6 Scala的类型系统 中
- 2016 第四讲 Scala模式匹配、类型系统彻底精通与Spark源码阅读
- 第4讲:Scala模式匹配、类型系统彻底精通与Spark源码阅读
- Scala类型系统——高级类类型(higher-kinded types)
- Scala类型系统编程