26

Is there a predefined function x in Scala that combine 2 Options so that

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

3 回答 3

49

Yes, this is the orElse method. It chooses the first defined value, or None if neither is defined.

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)
于 2013-01-13T16:13:17.297 回答
4

手动操作并不难:

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)
于 2013-01-13T16:14:28.150 回答
4

在问题评论中,你提到你不能拥有Some(a)and 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)
于 2013-01-13T22:58:42.773 回答