How to combine Option values in Scala?

Posted by Jeff on Stack Overflow See other posts from Stack Overflow or by Jeff
Published on 2010-04-26T09:42:35Z Indexed on 2010/04/26 11:33 UTC
Read the original article Hit count: 153

Filed under:
|

Hi!

I want to be able to apply an operation f: (T,T) => T to two Option[T] values in Scala. I want the result to be None if any of the two values is None.

More specifically, I want to know if is there a shorter way to do the following:

def opt_apply[T](f: (T,T) => T, x: Option[T], y: Option[T]): Option[T] = {
  (x,y) match {
    case (Some(u),Some(v)) => Some(f(u,v))
    case _ => None
  }
}

I have tryied (x zip y) map {case (u,v) => f(u,v)} but the result is an Iterator[T] not an Option[T].

Any help will be appreciated. Thanks.

© Stack Overflow or respective owner

Related posts about scala

Related posts about type-conversion