A Java-like implementation

This implementation directly reflects what we have in the previous diagram. First, let's see what our Person class will look like:

class Person(builder: PersonBuilder) {  val firstName = builder.firstName  val lastName = builder.lastName  val age = builder.age}

As we can see in the preceding code, it takes a builder and uses the values set in the builder for initialization of its fields. The builder code will look like the following:

class PersonBuilder {  var firstName = ""  var lastName = ""  var age = 0  def setFirstName(firstName: String): PersonBuilder = {    this.firstName = firstName    this  }  def setLastName(lastName: String): PersonBuilder = {    this.lastName = lastName    this  }  def setAge(age: Int): PersonBuilder = {

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.