将2个选项合并为1

时间:2013-01-13 16:11:45

标签: scala scala-option

Scala中是否存在预定义函数x,它将2个选项组合在一起,以便

Some(a) x None => Some(a)
None x Some(b) => Some(b)
None x None => None

3 个答案:

答案 0 :(得分:43)

是的,这是orElse方法。它选择第一个定义的值,如果两者都没有定义,则选择None

scala> Some(1) orElse None
res0: Option[Int] = Some(1)

scala> None orElse Some(1)
res1: Option[Int] = Some(1)

scala> None orElse None
res2: Option[Nothing] = None

scala> Some(1) orElse Some(2)
res3: Option[Int] = Some(1)

答案 1 :(得分:3)

手工操作并不难:

scala> val a = Some(1)
a: Some[Int] = Some(1)

scala> val b = Some(2)
b: Some[Int] = Some(2)

scala> Seq(a,b).flatten.headOption
res0: Option[Int] = Some(1)

答案 2 :(得分:3)

在问题评论中,你提到你不能拥有Some(a)Some(b),所以你真正拥有的是Option[Either[Int,Int]]。在这种情况下,您可以使用x.map(_.merge)返回Option[Int],例如

scala> val x:Option[Either[Int,Int]] = Some(Left(2))
x: Option[Either[Int,Int]] = Some(Left(2))

scala> x.map(_.merge)
res0: Option[Int] = Some(2)
相关问题