Scala类型 10 :交集类型(intersection type)与联合类型(union type)

来源:互联网 发布:淘宝游戏交易网 编辑:程序博客网 时间:2024/05/22 08:23
</pre><p>交集类型(<em>intersection type</em>):</p><p>Scala中,复合类型(compound type)既交集类型。表达形式:</p><p><pre name="code" class="java">X with Y with Z...

联合类型(union type):

联合类型的表现形式应该为:

X or Y or Z...

在Scala中没有语法形式的支持union type;但可以通过一些技巧实现。

StackOverflow上有两种实现方式。

  1. 通过隐式转换(上下文界定):
    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")  }}
    Scala的类型推断也有其影子,可阅读源码。
  2. Currying方式:coming soon...
0 0
原创粉丝点击