scalafunctional-programming

Iterate over Option instances until the first non-empty is found


I have a number of functions that return Option values, like this

case class A()
case class B() 
case class C()

def optionA(): Option[A] = None
def optionB(): Option[B] = Some(B())
def optionC(): Option[C] = Some(C())

What I want to do is, I want to run these functions in sequence, but only until one of the functions returns an Option with a value (a Some). Then I want to have that value returned, without running the remaining functions.

This is my current implementation

val res:Option[Any] = Stream(
  () => optionA(),
  () => optionB(),
  () => optionC()
) .map(f => f())
  .filter(opt => opt.isDefined)
  .head

For the function implementations above, this applies optionA and optionB, gives me a Some(B()), and it never runs optionC, which is what I want.

But I'd like to know if there is is a better/simple/alternative implementation.

Something like val findFirst = optionA compose optionB compose optionC?


Solution

  • optionA().orElse(optionB()).orElse(optionC())
    

    orElse will not evaluate its argument if this is defined.

    Or if you have already the options in a collection/stream, you might do

    options.find(_.isDefined).flatten