Scala CASE classes July 26, 2012
When you create a case class in scala say like
case class Something (id: Int)
you get the following from the compiler:
- the apply method so you can write Something(4) instead of new Something(4) when you are creating your objects
- the compiler adds the val since all the fields are immutable
- you get a copy function to create modified copies of your object like so: Something(6).copy(something = 7) and by using named parameters you can change only the value that changes.
Benefits of case classes:
- immutability, you can count on them not changing after they are created
- very nice to use in pattern matching
- very nice to use with tree structures and sealed classes
- meaningfull equals, hashCode and toString methods, especiall they first 2 might not be trivial to write.