Search code examples
scalalazy-evaluationscala-optioncoalescing

Lazily coalesce Options in Scala


I have several ways of calculating a value, in decreasing preference.

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

Each of these returns an Option. I want to "coalesce" these and get an Option which the the value returned by the first Some of these, or None if all returned None.

Of course, if firstWay() returns a Some, I shouldn't calculate the rest.

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


Solution

  • firstWay().orElse(second() + way()).orElse(orA(thirdWay()))
    

    orElse's argument is lazily evaluated.

    See the documentation.