How to combine Option values in Scala?

Jeff picture Jeff · Apr 26, 2010 · Viewed 13.8k times · Source

I want to be able to apply an operation f: (T,T) => T to 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 there is 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].

Answer

missingfaktor picture missingfaktor · Apr 26, 2010
scala> val (x, y) = (Some(4), Some(9))
x: Some[Int] = Some(4)
y: Some[Int] = Some(9)

scala> def f(x: Int, y: Int) = Math.max(x, y)
f: (x: Int,y: Int)Int

scala> for { x0 <- x; y0 <- y } yield f(x0, y0)
res26: Option[Int] = Some(9)

scala> val x = None
x: None.type = None

scala> for { x0 <- x; y0 <- y } yield f(x0, y0)
res27: Option[Int] = None