Alex Rivera | Logout

for..else for Option types in Scala?

Asked 2011-07-31T17:48:25.973
17

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?

Edit
Report

3 Answers

27

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.

answered 2011-07-31T19:13:46.667
13

You could pattern match both Options at the same time:

(xMaybe, yMaybe) match {
  case (Some(x), Some(y)) => "x and y are there"
  case _ => "x and/or y were None"
}
answered 2011-07-31T17:57:15.967
0

For scaling to many options, try something along these lines:

 def runIfAllSome[A](func:(A)=>Unit, opts:Option[A]*) = {
   if(opts.find((o)=>o==None) == None) for(opt<-opts) func(opt.get)
 }

With this, you can do:

scala> def fun(i:Int) = println(i)
fun: (i: Int)Unit

scala> runIfAllSome(fun, Some(1), Some(2))
1
2

scala> runIfAllSome(fun, None, Some(1))

scala>
answered 2011-07-31T17:59:06.193

Your Answer