The idiomatic way of writing nested pattern matching with parameters in Scala is done using the map , flatMap , orElse and getOrElse .
You use map if you want to continue processing the contents of the option and save the optional behavior:
So instead:
val opt: Option[Int] = ??? opt match { case Some(x) => Some(x + 1) case None => None }
You would do this:
val opt: Option[Int] = ??? opt.map(_ + 1)
This chaining is much more natural:
opt.map(_ + 1).map(_ * 3).map(_ - 2)
flatMap pretty similar, but is used when your further operations also return a parameter type.
In your specific example, orElse seems to be the most tailored solution. You can use orElse to return the option itself if it is not empty, or return an argument. Note that the argument is lazily evaluated, so it is really equivalent to the nested pattern matching / if -then-else.
def foo = { f1().orElse(f2()) .orElse(f3()) .orElse(f4()) }
You can also combine them with getOrElse if you want to get rid of the option. In your example, you seem to be returning the final f4 , as if it were not returning Option , so you would do the following:
def foo = { f1().orElse(f2()) .orElse(f3()) .getOrElse(f4()) }
source share