Search code examples
scalatagsoption-type

Canonical way to work on Option elements in Scala


As an example, I want to apply a function f: (Int,Int) => Int to two elements of type Option[Int]. My thoughts were something like (a,b).zipped.map(f), but this yields a List, and I want to get a new Option[Int] as result.

scala> def f(a:Int,b:Int) = a*b
f: (a: Int, b: Int)Int

scala> val x = Some(42)
x: Some[Int] = Some(42)

scala> val y:Option[Int] = None
y: Option[Int] = None

scala> (x,y).zipped.map(f)//I want None as a result here
res7: Iterable[Int] = List()

How can this be done without explicitly branching?


Solution

  • Just like many other operations in scala this can be done via for comprehension:

    def f(a:Int,b:Int) = a*b
    for (x <- maybeX; y <- maybeY) yield f(x, y)