Skip to content

Instantly share code, notes, and snippets.

@edmundnoble
Forked from andimiller/typesafebuilder.scala
Last active October 14, 2018 16:39
Show Gist options
  • Save edmundnoble/beaded6455c25c4edaf960e7f7606196 to your computer and use it in GitHub Desktop.
Save edmundnoble/beaded6455c25c4edaf960e7f7606196 to your computer and use it in GitHub Desktop.
object TypeSafeBuilder {
type F
type T
case class Cat(name: String, age: Int)
object CatBuilder {
def apply() = new CatBuilder[F, F](None, None)
implicit class BuildableCatBuilder(cb: CatBuilder[T, T]) {
def build(): Cat = cb.hiddenBuild()
}
}
class CatBuilder[A, B] private (name: Option[String], age: Option[Int]) {
def withName(s: String) = new CatBuilder[T, B](Some(s), age)
def withAge(a: Int) = new CatBuilder[A, T](name, Some(a))
private def hiddenBuild(): Cat = Cat(name.get, age.get)
}
CatBuilder().withAge(2).withName("Terry").build() // works
CatBuilder().withName("Bob").build() // doesn't compile
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment