Scala – Pattern Matching & Case Classes

Pattern matching is also applied to case classes. Rather patter matching is always discussed along with case classes. Let’s see how we can apply pattern matching to case classes. Let’s look at an example. See Below

case class Person(firstName: String, lastName: String, age: Int, emailId:String)

val John = new Person ("John","Doe",20,"[email protected]")
val Tim = new Person("Tim","Cole",25,"[email protected]")
val Jane = new Person("Jane","Doe",21,"[email protected]")
val Frank = new Person("Frank","Anthony",22,"[email protected]")

def checkSurname(p:Person):String = {
  case Person(_,"Doe",_,_) => println("Found a Doe!")
  case Person(_,"Cole",_,_) => println("Found a Cole!!")
  case _ => println("Unknown Last Name")
}

//Prints - Found a Doe!
checkSurname(John)

//Prints - Found a Cole!
checkSurname(Tim)

//Prints - Unknown Last Name
checkSurname(Frank)

In the above example, there is a Person case class defined and a match-case pattern matching function is defined which checks the lastName element of the Person class. If the lastName is Doe it prints that it has “Found a Doe!” and if it lastName is Cole it prints it has “Found a Cole!!”, otherwise, it prints “Unknown Last Name”.

Let’s start to mix up – In one of the first blog entry of Pattern matching we had discussed Or clause in values. We can use it in case classes as well. See Below

case class Person(firstName: String, lastName: String, age: Int, emailId:String)

val John = new Person ("John","Doe",20,"[email protected]")
val Tim = new Person("Tim","Cole",25,"[email protected]")
val Jane = new Person("Jane","Doe",21,"[email protected]")
val Frank = new Person("Frank","Anthony",22,"[email protected]")

def checkSurname(p:Person):String = {
  case Person(_,"Doe"|"Cole",_,_) => println("Found a Doe or Cole!")
  case _ => println("Unknown Last Name")
}

//Prints - Found a Doe or Cole!
checkSurname(John)

//Prints - Found a Doe or Cole!
checkSurname(Tim)

//Prints - Unknown Last Name
checkSurname(Frank)

The result is whenever the lastName is Cole or Doe it will print “Found a Doe or Cole!”.

Now let’s apply the gaurd clause to the case classes as well. See Below

case class Person(firstName: String, lastName: String, age: Int, emailId:String)

val John = new Person ("John","Doe",20,"[email protected]")
val Tim = new Person("Tim","Cole",25,"[email protected]")
val Jane = new Person("Jane","Doe",21,"[email protected]")

def checkAge(p:Person):String = {
  case Person(_,"Doe",_,_) => if (p.age>20)
    println(s"${p.firstName} Doe's Age is greater than 20")
  case _ => println("Unknown Last Name")
}

//Prints - Jane Doe's Age is greater than 20
checkAge(Jane)

//Prints - Unknown Last Name
checkAge(Tim)

In the above example, checkAge method checks if the lastName is Doe and also checks if the age is greater than 20. If both the conditions are satisfied it prints out a message.

Before we close this blog entry, let’s bring in the collections into the mix as well. Let’s create a List of Persons and then apply the pattern matching using map operator. See Below

case class Person(firstName: String, lastName: String,age: Int, emailId:String)

val John = new Person ("John","Doe",20,"[email protected]")
val Tim = new Person("Tim","Cole",25,"[email protected]")
val Jane = new Person("Jane","Doe",21,"[email protected]")
val Frank = new Person("Frank","Anthony",22,"[email protected]")

def sayHello(p:Person):Any = p match {
  case Person(_,"Doe"|"Cole",_,_) => println(s"Hello, ${p.firstName}!")
  case _ => println("Unknown Last Name")
}

//Add case class objects to list.
val people = List[Person](John,Tim,Jane,Frank)

//Using map function to call sayHello function
//on a List of Persons
people.map(p=>sayHello(p))

Needless to say, you can also apply the guard clause as well. Hopefully this entry has been helpful in increasing your understanding of pattern matching.

Keep Learning!

Leave a Comment