danny.lesnik
danny.lesnik

Reputation: 18639

What class is this Builder pattern extending?

I found an interesting scala implementation of Builder pattern, but I can't understand what a few lines mean:

  case class Built(a:Int, b:String){}
  trait Status
  trait Done extends Status
  trait Need extends Status

  class Builder[A<:Status,B<:Status] private(){
      private var built = Built(0,"")
      def setA(a0:Int)={
        built = built.copy(a=a0)
        this.asInstanceOf[Builder[Done,B]] 
      }
      def setB(b0: String) = { 
          built = built.copy(b = b0) 
          this.asInstanceOf[Builder[A,Done]] 
      }
     def result(implicit ev: Builder[A,B] <:< Builder[Done,Done]) = built 
  }

  object Builder{
    def apply() =  new Builder[Need,Need]
  }

1) What does private() mean in class Builder[A<:Status,B<:Status] private() class declaration?

2) What is the meaning of implicit ev: Builder[A,B] <:< Builder[Done,Done] in result function?

Upvotes: 1

Views: 252

Answers (2)

Kigyo
Kigyo

Reputation: 5768

1)

The private means that the primary constructor for Builder can not be accessed from outside.

Since there are no other constructors, the only way to get an instance is through the companion object with the apply method.

Example:

val builder = Builder()

2)

You have methods in Builder to set both parameters for the Built case-class. The method result gives you the constructed Built-instance. The evidence makes sure that you have set both parameters and will not allow you to create an instance if you didn't do it.

Example (I did not test this, so please correct me if I am wrong):

val builderA = Builder().setA(3)
val resultA = builderA.result //should not compile because this is Builder[Done, Need]
val builderAB = builderA.setB("hello") //now this is Builder[Done, Done]
val resultAB = builderAB.result //should compile and yield Built(3, "hello")

Upvotes: 5

Jason Oviedo
Jason Oviedo

Reputation: 529

For your first question, the keyword private in this position means the constructor for the class is private.

Upvotes: 1

Related Questions