Let's say I have a list of functions returning Option[Int] and I want to return the result of the first one returning Some(…), and not compute the rest of the functions after it. For example:
val list = List(
() => { println("a"); None },
() => { println("b"); Some(1) },
() => { println("c"); Some(2) },
() => { println("d"); None }
)
In this case, the result will be Some(1), and it will print only a and b (since the rest is not computed).
My solution was
list.foldLeft(Option.empty[Int]) { (a, b) => a orElse b() }
The question if there's a more elegant/concise way of doing it, or maybe some library?
list.view.flatMap(_()).headOption
a and b are only called once. c and d are never invoked or even iterated over. Returns None if there are no Some() values.
The .view wouldn't be needed if list was type LazyList.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With