Search code examples
scalascala-option

Scala Option ||


I want to get the value of one of several Option in scala, like this:

def or(a:Option[Int], b:Option[Int]):Option[Int]=
    if (a.isDefined) a else b

val a= Option(1)
val b= Option(2)
or(a,b).get

but I wonder why isn't the || operator defined for Option? Is there a more idiomatic way of doing this?


Solution

  • Use orElse.

    scala> Some(1) orElse Some(2)
    res0: Option[Int] = Some(1)
    
    scala> (None: Option[Int]) orElse Some(2)
    res1: Option[Int] = Some(2)