Home > Mobile >  Scala avoid case _ => in matching
Scala avoid case _ => in matching

Time:01-04

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.

CodePudding user response:

A match is a function like most things in Scala, so it returns a value and you need to return something for every possible case. If you are not doing anything in case _ then you are returning Unit 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 of Option/orElse, or find/collectFirst on a list of operations.

  •  Tags:  
  • Related