Case class
case class adds a lot of useful features to the normal class. It is handy to build lightweight data structures.
case Person(name: String, age: Int)
val jim = new Person("Jim", 34)
The features are as followed:
-
Class parameters are fields.
jim.name // It works -
It's sensible to
toString.println(jim.toString) // output: Person(Jim, 34) println(jim) // It's same as the previous line. -
equalsis implemented.val jim2 = new new Person("Jim", 34) println(jim == jim2) // true -
copyis very useful.// copy jim and set age to 13 val jim3 = jim.copy(age = 13) -
Case classes have companion objects
val mary = Person("Mary", 20) -
Case classes are serializable.
It's very useful in the framework Akka.
-
Case classes have extractor patterns.
It means they can be used in pattern matching.
We can also create case object.
case object Cat