How can I avoid always putting
case _ =>
at the end in Scala matching? It is sometimes possible that other values will be matched, but I only want to do something with the cases above the "case _ =>" case.
How can I avoid always putting
case _ =>
at the end in Scala matching? It is sometimes possible that other values will be matched, but I only want to do something with the cases above the "case _ =>" case.
A
match
is a function like most things in Scala, so it returns a value and you need to return something for every possiblecase
. If you are not doing anything incase _
then you are returningUnit
which, in turn, means that the code is relying on side effects and is non-functional.So the best way to reduce the use of empty
case _ =>
in your code is to make it more functional, since this isn't used in functional code.The alternative is to use a different mechanism for a multi-way branch, such as chained
if
, or chains ofOption/orElse
, orfind/collectFirst
on a list of operations.