Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).
like image 820
Yuchen Avatar asked Oct 16 '25 03:10

Yuchen


1 Answers

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

foo1 orElse foo2
like image 198
Tim Avatar answered Oct 17 '25 19:10

Tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!