4.14. Generating Boilerplate Code with Case Classes
Problem
You’re working with match expressions, actors, or other situations
where you want to use the case class syntax to
generate boilerplate code, including accessor and mutator methods, along
with apply, unapply, toString, equals, and hashCode methods, and more.
Solution
Define your class as a case class, defining any parameters it needs in its constructor:
// name and relation are 'val' by defaultcaseclassPerson(name:String,relation:String)
Defining a class as a case class results in a lot of boilerplate code being generated, with the following benefits:
An
applymethod is generated, so you don’t need to use thenewkeyword to create a new instance of the class.Accessor methods are generated for the constructor parameters because case class constructor parameters are
valby default. Mutator methods are also generated for parameters declared asvar.A good, default
toStringmethod is generated.An
unapplymethod is generated, making it easy to use case classes in match expressions.equalsandhashCodemethods are generated.A
copymethod is generated.
When you define a class as a case class, you don’t have to use the
new keyword to create a new
instance:
scala>case class Person(name: String, relation: String)defined class Person // "new" not needed before Person scala>val emily = Person("Emily", "niece")emily: Person = Person(Emily,niece)
Case class constructor parameters are val by default, so accessor methods are generated for ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access