• Articles
  • Tutorials
  • Interview Questions

Scala Pattern Matching and Case Class - A Comprehensive Guide

Scala Pattern Matching

It is a generalization of C or Java’s switch statement. This matching method is used instead of a 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 that will be performed if the pattern matches. A symbol => is used to separate the pattern from the expressions.

Watch this Apache-Spark-Scala video

Video Thumbnail

e.g.

object Intellipaat {
def main(args: Array[String]) {
println(matchValue(2))
}
def matchValue(i: Int): String = i match {
case 1 => "one"
case 2 => "two"
case 3=> "three"
case _=> "unknown"
}
}

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

Case Classes in Scala

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

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

Certification in Bigdata Analytics

Syntax

case class Calculator(Value: Type)

e.g.

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
}

Output
Hello abc
Hello xyz
ID: 3, Employee: pqr

Course Schedule

Name Date Details
Big Data Course 14 Dec 2024(Sat-Sun) Weekend Batch View Details
21 Dec 2024(Sat-Sun) Weekend Batch
28 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Technical Research Analyst - Big Data Engineering

Abhijit is a Technical Research Analyst specialising in Big Data and Azure Data Engineering. He has 4+ years of experience in the Big data domain and provides consultancy services to several Fortune 500 companies. His expertise includes breaking down highly technical concepts into easy-to-understand content.