Scala:链接多个 Option.when 调用

Scala: chaining multiple Option.when calls

我的代码为:

Option.when(condition)(evaluation)

..如果第一个失败,我想添加另一个条件,基本上是伪代码:

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

那么链接多个 Option.when 的可接受方式是什么?

您可以使用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)

更新:使用惰性评估示例

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)