Options in Scala

I have several ways to calculate a value while decreasing preferences.

firstWay() second() + way() orA(thirdWay()) 

Each of them returns an Option . I want to "combine" them and get an Option whose value is returned first by Some of them, or None if all are returned by None .

Of course, if firstWay() returns a Some , I should not calculate the rest.

What is the most idiomatic (or at least reasonably readable) way to do this?

+7
scala lazy-evaluation scala-option
source share
2 answers
 firstWay().orElse(second() + way()).orElse(orA(thirdWay())) 

orElse argument is lazily evaluated.

See the documentation .

+11
source share

If you have enough ways for Karol to respond, it becomes uncomfortable or does not know in advance how many:

 val options: Stream[Option[A]] = ... // in the example: firstWay() #:: (second() + way()) #:: orA(thirdWay()) options.foldLeft[Option[A]](None)(_.orElse(_)) 
+1
source share

All Articles