Flat 20% & upto 50% off + Free additional Courses. Hurry up!

Pattern Matching and Case Classes


Pattern Matching

It is a generalization of C or Java’s switch statement. In this match method is used instead switch statement. It is defined in Scala’s root class Any and therefore is available for all objects. The match method takes a number of cases as an argument. Each alternative takes a pattern and one or more expressions which will be performed if the pattern matches. A symbol => is used to separate the pattern from the expressions.


object Intellipaat {

def main(args: Array[String]) {



def matchValue(i: Int): String = i match {

case 1 => "one"

case 2 => "two"

case 3=> "three"

case _=> "unknown"





If patterns are of different type in different cases the use Any except Int and String in above example.


Case Classes

These are the special types of classes which are used for pattern matching with case expressions. By adding case keyword there are number of advantages which are:

  • Compiler automatically changes the constructor arguments into immutable fields.
  • Compiler automatically includes equals, hashCode and toString methods to the class


case class Calculator(Value: Type)


object Intellipaat {

def main(args: Array[String]) {

val a = new employee(1, “abc”)

val b  = new employee(2, “xyz”)

val c  = new employee(3, “pgr”)

for (employee <- List(a, b, c)) {

employee match {

case employee(1, “abc”) => println("Hello abc")

case employee(2, “xyz”) => println(“Hello xyz”)

case employee(id, employee_name) => println("ID: " +id + ", Employee:" + employee_name)




case class employee(id: Int, employee_name: String) // case class



Hello abc

Hello xyz

ID: 3, Employee: pqr


"0 Responses on Pattern Matching and Case Classes"

Leave a Message

100% Secure Payments. All major credit & debit cards accepted Or Pay by Paypal.

Sales Offer

  • To avail this offer, enroll before 28th February 2017.
  • This offer cannot be combined with any other offer.
  • This offer is valid on selected courses only.
  • Please use coupon codes mentioned below to avail the offer

Sign Up or Login to view the Free Pattern Matching and Case Classes.