What is the Scala equivalent to a Java builder pattern?

前端 未结 5 579
遇见更好的自我
遇见更好的自我 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:58

    It's the same exact pattern. Scala allows for mutation and side effects. That said, if you'd like to be more of a purest, have each method return a new instance of the object that you're constructing with the element(s) changed. You could even put the functions within the Object of a class so that there's a higher level of separation within your code.

    class Pizza(size:SizeType, layers:List[Layers], toppings:List[Toppings]){
        def Pizza(size:SizeType) = this(size, List[Layers](), List[Toppings]())
    
    object Pizza{
        def onTopOf( layer:Layer ) = new Pizza(size, layers :+ layer, toppings)
        def withTopping( topping:Topping ) = new Pizza(size, layers, toppings :+ topping)
    }
    

    so that your code might look like

    val myPizza = new Pizza(Large) onTopOf(MarinaraSauce) onTopOf(Cheese) withTopping(Ham) withTopping(Pineapple)
    

    (Note: I've probably screwed up some syntax here.)

提交回复
热议问题