Home > Software design >  Scala: chaining multiple Option.when calls
Scala: chaining multiple Option.when calls

Time:03-08

I have code as:

Option.when(condition)(evaluation)

..and I want to add another condition if first one fails, basically pseudo code like:

if(condition) {
    Some(evaluation)
} else if(another condition) {
   Some(another evaluation)
} else None

So what's the accepted way of chaining multiple Option.when?

CodePudding user response:

You can use Option.orElse

Option.when(false)(1).orElse(Option.when(false)(2)).orElse(Option.when(true)(3)) // Some(3)


// that's to say
val conditions: List[Boolean] = List(false, false, true)
val values: List[Int] = List(1,2,3)

val result: Option[Int] = conditions.zip(values).map {
    case (cond, value) => Option.when(cond)(value)
  }.reduceLeft(_ orElse _) // Some(3)

UPDATE: use lazy evaluate example

val n = 7

def randomBooleans(): Iterator[Boolean] = 
  Iterator.continually(scala.util.Random.nextBoolean()).take(n)

def randomValues(): Iterator[Int] = 
  Iterator.continually(scala.util.Random.nextInt()).take(n)

val res = randomBooleans()
      .zip(randomValues())
      .foldLeft(Option.empty[Int]) {
        case (res, (cond, value)) => {
          res.orElse(if (cond) {
            println(s"${cond} ${value}")
            Some(value)
          } else {
            println(s"${cond} ${value}")
            None
          })
        }
      }

println(s"result ${res}")

// false -1035387186
// false -1516857504
// true 1775201252
// result Some(1775201252)
  • Related