Scala类/类型,可以是其他未链接类集合中的一个



我有3个类从外部库(A, B, C)都扩展对象

我如何定义一种变量类型,只能保存这3种类型(及其子类)的值?像

val myVal: A or B or C (or their sub-classes if this is possible)

Scala不提供联合类型,但是你可以使用Coproduct,即Either类型的泛化。

Shapeless提供了一个很好的实现。

下面是一个直接来自the shapeless’s特性概述的例子

scala> type ISB = Int :+: String :+: Boolean :+: CNil
defined type alias ISB
scala> val isb = Coproduct[ISB]("foo")
isb: ISB = foo
scala> isb.select[Int]
res0: Option[Int] = None
scala> isb.select[String]
res1: Option[String] = Some(foo)

在这个例子中,您定义了Coproduct类型ISB,然后您可以使用select来提取您正在寻找的类型。select的结果是Option,因为isb可能持有也可能不持有该类型的实例。


其他不涉及库的方法可以在这里找到:如何定义"type disjunction"(联盟类型)?Miles Sabin (shapeless的作者)的这篇博文:http://milessabin.com/blog/2011/06/09/scala-union-types-curry-howard/

相关内容

最新更新