Scala – Pattern Matching

  • Post category:Scala
  • Reading time:5 mins read

What is Pattern Matching ?

Pattern matching is a mechanism for checking a value against a pattern. A successful match can also deconstruct a value into its constituent parts. 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.

Basic Syntax

import scala.util.Random
object Demo {
   def main(args: Array[String]) {
      val x: Int = Random.nextInt(10)
         x match {
           case 0 => println("zero")
           case 1 => println("one")
           case 2 => println("two")
           case 3 => println("three")
           case 4 => println("four")
           case 5 => println("five")
           case _ => println("other")
         }
      }
}

Example

object PatternMatchDemo {
   def main(args: Array[String]) {
      println(matchNumber(3))
   }
   
   def matchNumber(x: Int): String = x match {
      case 1 => "one"
      case 2 => "two"
      case _ => "many"
   }
}

Save the above program in PatternMatchDemo.scala. Compile and run the program as mentioned below.

scalac PatternMatchDemo.scala
scala PatternMatchDemo

Output

many

Explanation: The block with the case statements defines a function, which maps integers to strings. The match keyword provides a convenient way of applying a function to an object.

Match value against patterns of different type

object PatternMatchDemo{
   def main(args: Array[String]) {
      println(match("two"))
      println(match("test"))
      println(match(1))
   }
   
   def match(x: Any): Any = x match {
      case 1 => "One"
      case "two" => 2
      case y: Int => "Int Value"
      case _ => "Many"
   }
}

Save the above program in PatternMatchDemo.scala. Compile and run the program as mentioned below.

scalac PatternMatchDemo.scala
scala PatternMatchDemo

Output

2
many
one

Matching using Case Classes

object PatternMatchDemo{

case class Employee(name: String, age: Int, salary: Int)

def main(args: Array[String]) {
val john = new Employee("John", 25, 1000)
val tommy = new Employee("Tommy", 32, 2000)
val sony = new Employee("Sony", 32, 3000)

for (person <- List(john, tommy, sony)) { 
     person match { 
         case Employee("John", 25, 1000) => println("Match Found -> John") 
         case Employee("Tommy", 32, 2000) => println("Match Found -> Tommy") 
         case Employee(name, age, salary) => println("Age: " + age + " year, name: " + name + "?") } }
     }
}

Save the above program in PatternMatchDemo.scala. The following commands are used to compile and execute this program.

scalac PatternMatchDemo.scala
scala PatternMatchDemo

Output

Match Found -> John
Match Found -> Tommy
Age: 32 year, name: Sony?

NOTE : Adding the case keyword causes the compiler to add a number of useful features automatically.

  • Compiler automatically converts the constructor arguments into immutable fields (vals). The val keyword is optional. If you want mutable fields, use the var keyword. So, our constructor argument lists are now shorter.
  • Compiler automatically implements equals, hashCode, and toString methods to the class, which use the fields specified as constructor arguments. So, we no longer need our own toString() methods.
  • Body of the Employee class becomes empty because there are no methods that we need to define.