Scala Case Classes

Scala supports an interesting construct called case classes with the intent of creating immutable objects that can be used in pattern matching. This article provides a quick introduction to Scala case classes with examples.

A case class is created by adding the keyword case before the class definition.

case class Employee

Scala Case Classes can be used to automatically generate boilerplate code in classes that are primarily intended for storing data. Following methods are automatically generated when a class is defined as case class.

  1. apply() method is generated so that there is not need to use “new” keyword for creating a new case class instance.
  2. Getters are automatically defined.
    • Constructor parameters are considered val by default and hence only getters (accessors) are generated. If constructor parameters are declared var setters (mutators) are also automatically generated.
  3. toString() method is generated to simplify logging and debugging.
  4. equals() and hashCode() methods are generated which is used for instance comparison.
  5. unapply() method is generated which extracts/ decomposes the instance into tuples/ parts which enables using case classes in pattern matching.
  6. copy() method is generated which enables cloning an object.

Let us look at a simple case class example to understand the usage of generated methods. By just using the keyword case in class declaration Scala automatically generates all the required boilerplate code.

case class Employee (id: Int, name: String, dept: Int) {}object EmployeeTest {def main(args:Array[String]) {// "new" keyword is not used as apply() method is generatedval emp1 = Employee(1, "John", 100);// Getter methods for constructor parametersprintln( + " " + + " "  + emp1.dept)// Clone the object using copy methodvar emp2 = emp1.copy(2, "Smith")// Use toString()println(emp2)// Uses equals() and hasCode() for comparisonif ( emp1 == emp2 )println("Objects are same")elseprintln("Objects are different")// Extract information using unapply() methodemp1 match { case Employee(id, name, dept) => println(id + " " + name + " " + dept) }}}

This example produces the following output.

1 John 100Employee(2,Smith,100)Objects are different1 John 100

Proceed to read other Scala Tutorials.