As an example, we define a function that should convert 1, 3, 42 respectively to "foo", "bar", "qix" and all other integer to "X".
I've come up with 2 implementations :
The method f
need to be separate because it can be reuse in other context.
def f(i: Int): Option[String] = i match {
case 1 => Some("foo")
case 3 => Some("bar")
case 42 => Some("qix")
case _ => None
}
def g(i: Int) : String = f(i).getOrElse("X")
And :
def f_ : PartialFunction[Int, String] = {
case 1 => "foo"
case 3 => "bar"
case 42 => "qix"
}
def g_(i: Int) : String = f_.orElse { case _ => "X" }(i)
I tend to prefer the second because it avoid many repetitive Some(…)
WDYT ?