Skip to content

Instantly share code, notes, and snippets.

@retronym
Created November 8, 2009 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save retronym/229164 to your computer and use it in GitHub Desktop.
Save retronym/229164 to your computer and use it in GitHub Desktop.
Composable Builder Pattern using this.type in Scala
trait Buildable[T] {
def build: T
}
trait HeadBuilder extends Buildable[String] {
var eyeColor = "brown"
var hairColor = "red"
def withEyeColor(color: String): this.type = {
eyeColor = color
this
}
def withHairColor(color: String): this.type = {
hairColor = color
this
}
def build = "eyes: " + eyeColor + ", hair: " + hairColor
}
trait BodyBuilder extends Buildable[String] {
var limbCount = 4
def withNumLimbs(count: Int): this.type = {
limbCount = count
this
}
def build = "limbs: " + limbCount
}
class PersonBuilder extends HeadBuilder with BodyBuilder with Buildable[String] {
override def build: String = List(super[BodyBuilder].build, super[HeadBuilder].build).mkString(", ")
}
val person = new PersonBuilder().withEyeColor("blue").withNumLimbs(3).build
println(person) // limbs: 3, eyes: blue, hair: red
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment