Implement a type-safe builder pattern in Scala.
Instruction: Provide an example implementation of a type-safe builder pattern in Scala for constructing complex objects.
Updated
Track required fields in the builder's type parameters, restrict construction, and require evidence for each field at build. Compile-time presence checks and runtime value validation solve different problems.
object CarBuilder {
sealed trait State
sealed trait Missing extends State
sealed trait Present extends State
final class Car private[CarBuilder](
val engine: String, val tires: String, val paint: String)
final class Builder[
E <: State, T <: State, P <: State
] private[CarBuilder](engine: String, tires: String, paint: String) {
private def checked(value: String): String = {
require(value != null && value.trim.nonEmpty, "Nonblank value required")
value
}
def withEngine(value: String)(using E =:= Missing)
: Builder[Present, T, P] =
new Builder[Present, T, P](checked(value), tires, paint)
def withTires(value: String)(using T =:= Missing)
: Builder[E, Present, P] =
new Builder[E, Present, P](engine, checked(value), paint)
def withPaint(value: String)(using P =:= Missing)
: Builder[E, T, Present] =
new Builder[E, T, Present](engine, tires, checked(value))
def build(using E =:= Present, T =:= Present, P =:= Present): Car =
new Car(engine, tires, paint)
}
def begin: Builder[Missing, Missing, Missing] =
new Builder[Missing, Missing, Missing]("", "", "")
}
@main def builderExample(): Unit = {
val car = CarBuilder.begin.withPaint("blue")
.withEngine("electric").withTires("road").build
assert(car.engine == "electric" && car.tires == "road" && car.paint == "blue")
}
Any order is allowed, but each field can be set only once along a particular builder chain. Calling build early or setting a completed field again fails to compile because the required equality evidence is unavailable. The immutable initial builder can be reused to start independent chains. The private constructors prevent ordinary callers from inventing a completed state with missing data. Type equality evidence
The original requirement is presence, not a specific sequence, so three independent state parameters fit it. A fixed sequence could instead use separate staged interfaces. Nonblank runtime input is checked with require; richer domain constraints could return structured errors from setters. The type states do not prove compatibility of an engine and tires, authorization, or safety against deliberate casts, null evidence or reflection.