Scala Pattern Matching with case statement With Examples

Scala supports inbuilt pattern matching mechanism which is one of the more powerful feature. Pattern matching starts with the keyword case. Each includes a pattern or one or more expression that shall be evaluated if the pattern matches. An arrow symbol => separates pattern from the expressions.

Lets us consider a simple example of how to match against an integer value.

We created the object Stud and defined the method main and invoked studAgematch method by passing an Integer argument. The studAgematch method accepts an Integer argument age, defines various cases for ages 5,7,8,10 and other numbers and prints the statements enclosing the case. We are passing numbers 7,5 ,12 and hence the case matching these numbers are printed.

Run the program by typing Stud.main(null) and you will see below output in Scala shell.


In the above example we saw the cases for Integer data types but pattern matching can be done for string arguments as well.
Let us see an example for this below.

We created object Student with main method and invoked the matchAge method by passing the arguments with both string and integer data types. In the matchAge method, the first case is satisfied if the integer value is 7 and case y is executed if the integer value is other than 7. The second case with string “eight” is executed if the passed argument is of string value “eight” and for other default string values the case_ is executed.

Run the code by typing Student.main(null) and you will see below output.


Pattern Matching using case classes

Scala supports case classes that can be used for pattern matching with case expressions. These classes are standard classes with a modifier case.

Let us understand this concept through an example;

We create an object Stu with main method and create new student objects st1, st2 and st3. Using the for loop iterate through the list with objects st1, st2, st3 and st4 and use the case expressions with Student constructor by passing the values.

In the first case matching expression is the object Adam and second is for the name Reema and for other values the details are printed as specified in the last case. The student constructor is specified with id, name and age parameters for empty one.

Run the above code by typing Stu.main(null) and you will see below output.


Some quick points about the case classes pattern matching;

  • The case keyword tells the compiler to add additional features automatically.
  • The compiler automatically converts the constructor arguments into immutable fields. The val keyword is optional. If mutable fields are needed the var keyword can be used. The compiler implements equals, hashcode and toString methods using the fields specified as constructor arguments.

That’s all for now, we will look into more Scala features in coming posts.

By admin

Leave a Reply

%d bloggers like this: