Scala Pattern Matching with case statement

Filed Under: Scala

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.


object Stud {

def main(args:Array[String]) {
println(studAgematch(7))
println(studAgematch(5))
println(studAgematch(12))
}

def studAgematch(age:Int) : String = age match {

case 5 => "Student Age is 5 "
case 7 => "Student Age is 7"
case 8 => "Student Age is 8"
case 10 => "Student Age is 10"
case _ => "Student age is greater than 10"
}
}

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.


scala> Stud.main(null)
Student Age is 7
Student Age is 5 
Student age is greater than 10

Scala-case-statement

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.


object Student {

def main(args: Array[String]) {
println(matchAge("eight"))
println(matchAge("twelve"))
println(matchAge(7))
println(matchAge(9))
}

def matchAge(age: Any): Any = age match {
case 7 => "Age is Seven"
case "eight" => 8
case y: Int => "Age is greater than 7"
case _ => "Age is greater than 10"
}
}

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.


scala> Student.main(null)
8
Age is greater than 10
Age is Seven
Age is greater than 7

Scala-case-statement-any

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;


object Stu {

def main(args: Array[String]) {
val st1 = new Student(1,"Adam", 12)
val st2 = new Student(2,"John", 9)
val st3 = new Student(3,"Reena", 16)

for (st <- List(st1, st2, st3)) {

st match {
case Student(1,"Adam", 12) => println("Hello Adam")
case Student(3,"Reena", 16) => println("Hello Reena")
case Student(id,name, age) =>
println("Id: " + id + " Age: " + age + " Name: " + name)
}
}
}

case class Student(id:Int, name: String, age: Int)
}

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.


scala> Stu.main(null)
Hello Adam
Id: 2 Age: 9 Name: John
Hello Reena

Scala-case-statement-class

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.

Comments

  1. shivdutta says:

    Pankaj: I revised my scala concepts for interview from your website.
    Excellent explanation with short time

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages