Another alternative to the Builder pattern in Scala 2.8 is to use immutable case classes with default arguments and named parameters. Its a little different, but the effect is smart defaults, all the specified values โโand things that are specified only once with syntax checking ...
Below are used strings for values โโfor brevity / speed ...
scala> case class Pizza(ingredients: Traversable[String], base: String = "Normal", topping: String = "Mozzarella") defined class Pizza scala> val p1 = Pizza(Seq("Ham", "Mushroom")) p1: Pizza = Pizza(List(Ham, Mushroom),Normal,Mozzarella) scala> val p2 = Pizza(Seq("Mushroom"), topping = "Edam") p2: Pizza = Pizza(List(Mushroom),Normal,Edam) scala> val p3 = Pizza(Seq("Ham", "Pineapple"), topping = "Edam", base = "Small") p3: Pizza = Pizza(List(Ham, Pineapple),Small,Edam)
Then you can also use existing immutable instances as your own constructors ...
scala> val lp2 = p3.copy(base = "Large") lp2: Pizza = Pizza(List(Ham, Pineapple),Large,Edam)
James Strachan Jan 07 2018-11-11T00: 00Z
source share