Ronald
Ronald

Reputation: 187

Scala avoid case _ => in matching

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.

Upvotes: 0

Views: 637

Answers (1)

Tim
Tim

Reputation: 27431

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.

Upvotes: 4

Related Questions