Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a list of fallback functions

Tags:

scala

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?

like image 630
Ori Popowski Avatar asked Dec 30 '22 14:12

Ori Popowski


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.

like image 94
jwvh Avatar answered Jan 09 '23 03:01

jwvh