Created
November 8, 2009 08:03
-
-
Save retronym/229164 to your computer and use it in GitHub Desktop.
Composable Builder Pattern using this.type in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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