What is the Scala equivalent to a Java builder pattern?

前端 未结 5 577
遇见更好的自我
遇见更好的自我 2020-12-23 13:31

In the work that I do on a day to day in Java, I use builders quite a lot for fluent interfaces, e.g.: new PizzaBuilder(Size.Large).onTopOf(Base.Cheesy).with(Ingredien

5条回答
  •  天命终不由人
    2020-12-23 13:45

    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 values specified and things only specified once with syntax checking...

    The following uses Strings for the 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)
    

    You can then also use existing immutable instances as kinda builders too...

    scala> val lp2 = p3.copy(base = "Large")
    lp2: Pizza = Pizza(List(Ham, Pineapple),Large,Edam)
    

提交回复
热议问题