Simple Guidance For You In Case Class And Pattern Matching

scala futures
Reading Time: 2 minutes

Case classes are like regular classes that have default apply() method which handle object construction. There is no  need to use a new keyword to create an object.

Case class provides purely functional code with immutable objects. Case classes are a representation of a data structure with the necessary methods. It support pattern matching.

Syntax of case class:-

case class ClassName(Parameters)

Example:- 

case class Example(x: Int, y: Int)

object Main {
  def main(args: Array[String]): Unit = {

    val obj = Example(1, 2)    // creating object of Example
    println("x=" + obj.x)      // x=1
    println("y=" + obj.y)      //y=2

  }
}

When you create a case class with parameters, the parameters are Immutable (val) by default.

obj.x=3 

This line will not compile because you can’t reassign obj.x due to its immutability.

In case classes, comparisons between instances are done on basis of their structure not by their reference.

case class Person(name: String, age:Int)

val person1 = Person("Ram",23)
val person2 = Person("Ram",23)
val personAreTheSame=person1==person2  // true

Here, person1 and person2 are two different objects but value of each object is equal.

Pattern Matching

Pattern matching is a feature of Scala. 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.

Example:-

def PatternMatching(value: Int): Unit = value match {
    case 1 => print("One")
    case 2 => print("Two")
    case 3 => print("Three")
    case 4 => print("Four")
    case _ => print("No Matched")
  }

Here, In this line case _ is a default case if all other conditions do not match then the default case will execute.

Case Class with Pattern Matching

In Scala, Case classes 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 that are:-

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

Example:-

abstract class Notification
case class Mail(sender: String, tittle: String) extends Notification
case class SMS(number: String, message: String) extends Notification
case class CallRecorder(number: String, link: String) extends Notification
case class Call(number: String) extends Notification

object Main extends App {

  def showNotification(notification: Notification): String = {
    notification match {
      case Mail(sender, tittle) => s"Email from $sender with title: $tittle"
      case SMS(number, message) => s" SMS from $number! Message: $message"
      case CallRecorder(number, link) => s"Voice Recording from $number link:$link"
      case Call(number) => s"You received a call from $number"
    }
  }
}

Here in this example we have created an abstract class Notification then we created 4 case classes (Mail , SMS, CallRecorder, Call) that extend the Notification abstract class.
In showNotification method we are using case classes with pattern matching.

Conclusion

Through this blog, You will get the basic knowledge about pattern matching or case classes.The concept of pattern matching is a powerful feature of Scala and also it provides us with a more concise and readable code and ability to match elements against complex patterns.You will  also get to know about pattern matching with case classes.

Written by 

Vineet Chauhan is a Software Consultant at Knoldus Inc. His practice area is Scala. He is a good team worker. He is always ready to face any challenging task.

4 thoughts on “Simple Guidance For You In Case Class And Pattern Matching3 min read

Comments are closed.