Pattern matching in Scala is one of the most widely used and discussed topics. In simple terms, it is similar to the switch-case. Let’s use that familiarity to get a simple understanding of pattern matching and build up from there.
Let’s first look at a simple match-case expression and see how it works.
In the above example, we have a function called multiply, which takes a parameter and returns a value. If the value is 4 it will multiply the value by 3. Underscore _ acts as a catch-all for any other values and it will multiply by 2.
This is simple. But what if we want to apply the same logic for more than one patterns. Writing individual case statements would make the code unnecessarily long. Let’s apply an OR logic to the expression.
In the above example, we have a function called multiply, which takes a parameter and returns a value. If the value is 4 or 6 it will multiply the value by 3. Underscore _ acts as a catch-all for any other values and it will multiply by 2.
match-case can also be used to check the type. Which is a much cleaner way for type checking instead of an exception handler. See Below
In the above example, the code checks the input type of the parameter. There is no need of calling the instanceOf method.
Now let’s mix things up a bit. What if we want to multiply all numbers greater than or equal to 5 by 2 and less than 5 by 3. If anything else is passed let’s just return a message. Let’s add a bit more to match case – if statement. It is also called the guard clause. See Below
In the next entry let’s focus on applying pattern matching to collections.