A code example

There are actually three main ways in which we can represent the builder design pattern in Scala:

  • The classical way, as shown in the preceding diagram, is like other object-oriented languages. This way is actually not recommended, even though it is possible in Scala. It uses mutability in order to work, which contradicts the immutability principle of the language. We will show it here for completeness and in order to point out how much easier it is to achieve the builder design pattern using simple features of Scala.
  • Using case classes with default parameters. We will see two versions—one that validates the parameters and another one that doesn't.
  • Using generalized type constraints.

We will focus on these in the next few ...

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.