Lazily coalesce Options in Scala
Asked Answered
M

2

7

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?

Muttonchops answered 18/2, 2014 at 1:14 Comment(0)
S
11
firstWay().orElse(second() + way()).orElse(orA(thirdWay()))

orElse's argument is lazily evaluated.

See the documentation.

Sacramental answered 18/2, 2014 at 1:40 Comment(0)
H
2

If you have enough ways that Karol's answer becomes unwieldy, or don't know in advance how many:

val options: Stream[Option[A]] = ...
// in the example: firstWay() #:: (second() + way()) #:: orA(thirdWay())

options.foldLeft[Option[A]](None)(_.orElse(_))
Humanize answered 18/2, 2014 at 10:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.