How to implement a list of fallback functions

Viewed 93

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?

1 Answers
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.

Related