scalascala-optionpartial-functions

How to getOrElse with another Option in Scala


Let's assume that we have an option foo1 and an option foo2:

val foo1: Option[Foo]
val foo2: Option[Foo]

Is there an operator/function that allows me to return the value of the foo2 when foo1 is None?

val finalFoo: Option[Foo] = foo1.getOrElseOption(foo2)

The above getOrElseOption does not exist obviously. I know we can do sth like this, but it is somewhat verbose and hard to understand:

foo1.map(Some(_)).getOrElse(foo2).

Solution

  • Option works a bit like a partial function, so orElse will do what you want:

    foo1 orElse foo2