0

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.

4
  • 4
    Case matching must be exhaustive. If you only care about the other cases, you still need to ensure your program handles the other cases somehow. Commented Jan 2, 2022 at 21:51
  • In some case a simple procedural if structure might be simpler. See this not-duplicate yet related question comparing usages. At least one answer also covers why such a case _ is required. Commented Jan 2, 2022 at 22:17
  • 2
    It's a code smell if you have a lot of these Commented Jan 3, 2022 at 1:49
  • If you match on sealed trait case _ can be safely skipped, nevertheless code has to be edited if new implementation of that trait is added. Commented Jan 3, 2022 at 11:12

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.