Implementation with a case class

The preceding builder design pattern looks nice and clear, but it requires writing some extra code and creating boilerplate. Moreover, it requires us to have mutable fields in the PersonBuilder class, which is against some of the principles in Scala.

Preferring immutability Immutability is an important principle in Scala and it should be preferred. The builder design pattern with case classes uses immutable fields and this is considered a good practice.

Scala has case classes, which make the implementation of the builder pattern much simpler. Here is what it will look like:

case class Person(  firstName: String = "",  lastName: String = "",  age: Int = 0)

The use of this case class is similar to how the preceding ...

Get Scala Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.