scalamonadsfor-comprehension

for..else for Option types in Scala?


Suppose I have two Options and, if both are Some, execute one code path, and if note, execute another. I'd like to do something like

for (x <- xMaybe; y <- yMaybe) {
  // do something
}
else {
  // either x or y were None, handle this
}

Outside of if statements or pattern matching (which might not scale if I had more than two options), is there a better way of handling this?


Solution

  • Very close to your syntax proposal by using yield to wrap the for output in an Option:

    val result = { 
      for (x <- xMaybe; y <- yMaybe) yield {
        // do something
      }
    } getOrElse {
      // either x or y were None, handle this
    }
    

    The getOrElse block is executed only if one or both options are None.