Overview

Pattern matching is a mechanism for checking a value against a pattern. It is a more powerful version of the switch statement in Java and it can likewise be used in place of a series of if/else statements.

Syntax

A match expression has a value, the match keyword, and at least one case clause.

The val x above is a random integer between 0 and 10. x becomes the left operand of the match operator and on the right is an expression with four cases. The last case _ is a “catch all” case for any number greater than 2. Cases are also called alternatives.

Scala Pattern Matching Example

One

Here, match using a variable named a. This variable matches with best available case and prints output. Underscore (_) is used in the last case for making it default case.

Match expression can return case value also. In next example, we are defining method having a match with cases for any type of data. Any is a class in scala which is a super class of all data types and deals with all type of data. Let’s see an example.

In above example we are passing “Hello” string in search method so as per third case output will be Hello.

Hello

That’s all for pattern matching in Scala. Happy Learning!!

Leave a Reply

Your email address will not be published. Required fields are marked *