Implementing Option#map2 Working on an example from Functional Programming in Scala, I'm working on Option#map2:

override def map2[A, B, C](fa: Option[A],fb: Option[B])(f: (A, B) =&gt; C): Option[C] = {
  (fa, fb) match {
    case (None, _) =&gt; None
    case (_, None) =&gt; None
    case (_, _) =&gt; Some(f(fa.get, fb.get)) // runtime-safe get calls
  }
}


Is the above implementation reasonable? I presumed that, if either fa or fb were None, then so should be the returned value. Pattern matching seemed the most clean to me, but perhaps there's a cleaner or more concise way to write this method?
Your code is correct - it should work nicely.

The first thing that I would improve on is the // runtime-safe get calls. This is an anti-pattern in Scala and is generally discouraged. In this case you can use pattern matchings powerful extractors to get the value the Option is storing:

case (Some(a), Some(b)) =&gt; Some(f(a, b))


But instead of pattern matching the most elegant way to solve this problem is to use for comprehensions. It is functionally the same as your code:

override def map2[A, B, C](fa: Option[A], fb: Option[B])(f: (A, B) =&gt; C): Option[C] = {
  for {
    a &lt;- fa
    b &lt;- fb
  } yield f(a, b)
}


Since Option is essentially a collection with either zero or one element it can be used in for-comprehensions. The variable a will only be populated if fa is a Some. If either is None then nothing will be yielded and the result is None.