Skip to content

Instantly share code, notes, and snippets.

@andimiller
Last active October 14, 2018 16:38
Show Gist options
  • Select an option

  • Save andimiller/a2c9db501b20d6398abc0461659f309e to your computer and use it in GitHub Desktop.

Select an option

Save andimiller/a2c9db501b20d6398abc0461659f309e to your computer and use it in GitHub Desktop.

Revisions

  1. andimiller revised this gist Oct 13, 2018. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion typesafebuilder.scala
    Original file line number Diff line number Diff line change
    @@ -21,6 +21,6 @@ object TypeSafeBuilder {


    CatBuilder().withAge(2).withName("Terry").build() // works
    CatBuilder().withName("Bob").build() // doesn't compil;e
    CatBuilder().withName("Bob").build() // doesn't compile

    }
  2. andimiller created this gist Oct 13, 2018.
    26 changes: 26 additions & 0 deletions typesafebuilder.scala
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    object TypeSafeBuilder {

    sealed trait BuilderStatus
    object Satisfied extends BuilderStatus
    object NotSatisfied extends BuilderStatus

    case class Cat(name: String, age: Int)

    object CatBuilder {
    def apply() = new CatBuilder[NotSatisfied.type, NotSatisfied.type](None, None)
    implicit class BuildableCatBuilder(cb: CatBuilder[Satisfied.type, Satisfied.type]) {
    def build(): Cat = cb.hiddenBuild()
    }
    }

    class CatBuilder[A <: BuilderStatus, B <: BuilderStatus] private (name: Option[String], age: Option[Int]) {
    def withName(s: String) = new CatBuilder[Satisfied.type, B](Some(s), age)
    def withAge(a: Int) = new CatBuilder[A, Satisfied.type ](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 compil;e

    }