Using require statements

The type-safe builder we showed previously is nice, but it has some drawbacks:

  • Complexity
  • Mutability
  • A predefined order of initialization

However, it could be quite useful because it allows us to write code that will be checked for correct usage as soon as we compile it. Sometimes, compile-time validation is not required, though. If this is the case, we can make things extremely simple and get rid of the entire complexity using the already known case classes and the require statements:

case class Person(  firstName: String = "",  lastName: String = "",  age: Int = 0) {  require(firstName != "", "First name is required.")  require(lastName != "", "Last name is required.")}

If the preceding Boolean conditions are not satisfied, ...

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.