What are Case Classes in Scala

Reading Time: 2 minutes
Case Classes Image

Case Classes in Scala

Case classes in scala are regular classes with some extra toppings. Let’s discuss why they are high in demand.

A case class with no arguments is declared as a case object rather than a case class. By default, the case object can be serialized. A Case Object is also like an object, which has more attributes than a regular Object and Case classes in Scala are classes that can be decomposed using pattern matching. So compares instances structurally using the equal method.

In addition, Scala case classes are similar to regular classes except that they are useful for modeling immutable data and for pattern matching.

After that, By default case classes have public and immutable parameters. In addition, These support pattern matching, making it easier to write logical code.

Some of the characteristics of a Scala case class are as follows:

  • case class parameters are fields.
  • Scala produces methods like equals(), hashcode(), and toString() automatically as part of the case class.
  • case class has a copy method that is used to copy arguments and can override them.
  • An instance can be created without using the ‘new‘ keyword.
  • A default toString method is generated, which is helpful for debugging.

-> With apply you don’t need new & using the parameter as a field

case class CaseClassDemo(name: String) {
  // Using constructor parameter as field
  println(s"Hello, I am $name, How are you ?")
}
 case object CaseClassDemo extends App {
   val Rohan = CaseClassDemo("Rohan")
 }

Output : Hello, I am Rohan, How are you ?

-> copy method & equal method

object CaseClassDemo extends App {
  case class Fruits(name: String)
    val firstFruit = Fruits("Orange")
    val secondFruit = firstFruit.copy()
    println(secondFruit.name)
    println(firstFruit == secondFruit)
}

Output : Orange
         true

-> toString

object CaseClassDemo extends App {
  case class Fruits(name: String, age: Int)
    val fruit = Fruits("Orange", 15)
    val ageOfFruitInString = fruit.age.toString
    println("length of converted age is : " + ageOfFruitInString.length)
}

Output : length of converted age is : 2
case class Implementation

Conclusion

Firstly, Thank you guys for making it to the end of the blog I hope you gained some knowledge on how we can create a case class in Scala. Then, we learned about some important functions of case class.

Reference

For more details please visit the official documentation by using the link: https://docs.scala-lang.org/

Written by 

Pallav is working as Software Consultant at Knoldus Inc. He is a technology enthusiast and a keen learner with more than 1.5 years of experience. He works as a Quality Catalyst in the organization. He has a good understanding of programming languages like Java and Scala. He likes to listen to songs and playing table tennis.