27

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
giampaolo
  • 6,906
  • 5
  • 45
  • 73
Jens Schauder
  • 77,657
  • 34
  • 181
  • 348

3 Answers3

48

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)
Ben James
  • 121,135
  • 26
  • 193
  • 155
3

It's not hard to do it by hand:

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)
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
3

In the question comments, you mention you can't have Some(a) and Some(b), so what you really have is Option[Either[Int,Int]]. In that case, you can use x.map(_.merge) to get back to Option[Int], eg

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)
Kristian Domagala
  • 3,686
  • 20
  • 22
  • 2
    This is a very good point. It's suspicious to be using a type which so obviously has inhabitants that "can't happen" – Ben James Mar 16 '13 at 20:17
  • this might not work out so well though if he has two `Option[T]` returning functions though, or would it? – Erik Kaplun Feb 13 '14 at 03:11
  • 2
    My point was more that *if* the two `Some` cases *can't* happen, then it would be better to encode that in the type system. If there are 2 `Option[T]` values, then it must be assumed that they can both be `Some`. The `orElse` answer that Ben gave prioritises one option over the other, which may be valid. Using `Option[Either[T,T]]` though removes the need to make that decision. – Kristian Domagala Feb 13 '14 at 03:43