Scala “case” classes

Scala has a very nice “case” keyword which automatically triggers the compiler to build in some nice defaults for a class. These defaults include a default equals, toString, and copy method. It also defaults fields to being immutable and implements serializable for you.

For example, let’s say you need a data structure to represent a cell phone. Here’s a REPL example:

scala> case class CellPhone(manufacturer: String, model: String, version: String, firmware: String)
defined class CellPhone

scala> val galaxyS5 = new CellPhone("Samsung", "Galaxy", "S5", "5.1.2")
galaxyS5: CellPhone = CellPhone(Samsung,Galaxy,S5,5.1.2)

scala> //copy method

scala> val galaxyS6 = galaxyS5.copy(version = "S6", firmware = "1.1.1")
galaxyS6: CellPhone = CellPhone(Samsung,Galaxy,S6,1.1.1)

scala> //toString demo

scala> println(galaxyS5)

scala> println(galaxyS6)
CellPhone(Samsung,Galaxy,S5,5.1.2)

scala>//.equals

scala> println(galaxyS5 == galaxyS6)
false

The copy method deserves special attention. This method can be used as a way to preserve immutability.

scala> def upgradeFirmware(ph: CellPhone): CellPhone = {
     | ph.copy(firmware = "5.1.3")
     | }
upgradeFirmware: (ph: CellPhone)CellPhone

scala> val mikesPhone = new CellPhone("Samsung", "Galaxy", "S5", "5.1.2")
mikesPhone: CellPhone = CellPhone(Samsung,Galaxy,S5,5.1.2)

scala> upgradeFirmware(mikesPhone)
res2: CellPhone = CellPhone(Samsung,Galaxy,S5,5.1.3)

Read more about case classes in the online first edition of Programming in Scala.

Leave a Reply

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