-
-
Save edmundnoble/beaded6455c25c4edaf960e7f7606196 to your computer and use it in GitHub Desktop.
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
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