Case Class in Scala

Scala Tutorial

Senthil Nayagan
2 min readMar 11, 2019
Take Care, Santa Monica, California, USA | Photo Credit: Miguel Perales

Overview

Case classes are a special kind of classes created using the keyword case.

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

Case classes are good for modeling immutable data. When the Scala compiler sees a case class, it automatically adds a number of useful features or conveniences to our class as listed below:

  • Defines a factory method, apply() for creating new instances — we don’t need to use the keyword new to instantiate a class class .
  • Unless all arguments in the parameter list of a case class is declared as var, all arguments implicitly gets a val prefix — maintained as immutable fields and thus the “val” keyword is optional.
  • The compiler automatically implements equals, hashCode, and toString methods to the class.
  • Every case class has a method named copy that allows us to easily create a same or a modified copy of the class’s instance.
  • A companion object is created with the appropriate apply and unapply methods.

Like any other class, a case class can extend other classes, including trait and case classes. Case classes are Scala’s way to allow pattern matching on objects without requiring a large amount of boilerplate.

Abstract Case Class

When we declare an abstract case class, Scala won’t generate the apply
method in the companion object which makes sense as we can’t create an
instance of an abstract class.

Case Object

We can also create case objects that are singleton and serializable.

Case Class’s equals()

Case class’s equal method does deep comparison i.e. compared structurally, meaning, if we have two different instances of case class and their fields contain the same data then they are the same object.

scala> val person = Person(“John”, 20) 
scala> person == Person(“John”, 20)
res1: Boolean = true

Case Class’s copy()

Case class’s copy() method lets us make a copy of an object. Note that a “copy” is different than a clone, because with a copy we can change fields as desired during the copying process.

case class Worker(name: String, role: String)object CaseClassCopyMethod extends App {
val john = Worker("john", "sales")
val joe = john.copy(name="joe")
}

Benefits of Case Class

Generates the following boilerplate:

  • apply and unapply methods.
  • Accessor methods are created for each constructor parameter.
  • copy method.
  • equals, hashCode and toString methods.

--

--

Senthil Nayagan
Senthil Nayagan

Written by Senthil Nayagan

I am a Data Engineer by profession, a Rustacean by interest, and an avid Content Creator.

No responses yet