Coalescing options in Scala

How about:

values.flatten.headOption

This works since Option is implicitly convertible to Iterable, so flatten works much in the same way as a list of lists.


Shorter still, you could use collectFirst. This will do it in one step, with at most one traversal of the collection.

def coalesce[A](values: Option[A]*): Option[A] =
    values collectFirst { case Some(a) => a }


scala> coalesce(Some(1),None,Some(3),Some(4))
res15: Option[Int] = Some(1)

scala> coalesce(None,None)
res16: Option[Nothing] = None

Auto answer:

The native mechanism (without implementing a coalesce function) is the chaining of calls to orElse method:

> None.orElse(Some(3)).orElse(Some(4))
res0: Option[Int] = Some(3)

> Some(1).orElse(None).orElse(Some(3)).orElse(Some(4))
res1: Option[Int] = Some(1)

> None.orElse(None)
res2: Option[Nothing] = None