The beauty of Scala case classes

One of my favorite features in Scala are case classes. Below is an example of the declaration of a case class:

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

The declaration looks pretty simple, isn’t it?

Now let’s do it the java way:

public class Student {
  private String name;
  private int age;

  public Student(String name, int age) {
     this.name = name;
     this.age = age;
  }

  public String getName() {
    return this.name;
  }

  public String setName(String name) {
     this.name = name;
  }

  public int getAge() {
    return this.age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public boolean equals(Object obj) {
    ...
  }

  public int hashCode() {
    ...
  }

  public String toString() {
    ...
  }

Which method do you prefer.
Scala case classes are extremely powerful and their main use is not limited to writing abbreviated java beans.

By declaring a case class we get for free the equals, toString and hashCode methods. Nice, can it get any better? Yes….
You can easily create instances of a case class without having to declare a constructor and no need to use the new keyword:

val students = List(Student("John", 20), Student("David", 21))

Case classes are used for pattern matching. Pattern matching is similar to Java switch statements however it is many times more powerful. The example below shows a typical use for case classes with pattern matching:

abstract class Expression
case class Sum(a1:Int, a2:Int) extends Expression
case class Diff(a1:Int, a2:Int) extends Expression
case class Mult(a1:Int, a2:Int) extends Expression

def doOperation(expr:Expression):Int = expr matches {
  case Sum(a1, a2) => a1 + a2
  case Diff(a1, a2) => a1 - a2
  case Mult(a1, a2) => a1 * a2
}

Leave a Reply

Your email address will not be published. Required fields are marked *