Scala Language Extractors Case Class Extractors


A case class is a class with a lot of standard boilerplate code automatically included. One benefit of this is that Scala makes it easy to use extractors with case classes.

case class Person(name: String, age: Int)  // Define the case class
val p = Person("Paola", 42)  // Instantiate a value with the case class type

val Person(n, a) = p  // Extract values n and a
// n: String = Paola
// a: Int = 42

At this juncture, both n and a are vals in the program and can be accessed as such: they are said to have been 'extracted' from p. Continuing:

val p2 = Person("Angela", 1337)

val List(Person(n1, a1), Person(_, a2)) = List(p, p2)
// n1: String = Paola
// a1: Int = 42
// a2: Int = 1337

Here we see two important things:

  • Extraction can happen at 'deep' levels: properties of nested objects can be extracted.
  • Not all elements need to be extracted. The wildcard _ character indicates that that particular value can be anything, and is ignored. No val is created.

In particular, this can make matching over collections easy:

val ls = List(p1, p2, p3)  // List of Person objects => person match {
  case Person(n, a) => println("%s is %d years old".format(n, a))

Here, we have code that uses the extractor to explicitly check that person is a Person object and immediately pull out the variables that we care about: n and a.