Building big, immutable objects without using constructors having long parameter lists

前端 未结 9 799
星月不相逢
星月不相逢 2020-12-04 06:31

I have some big (more than 3 fields) objects that can and should be immutable. Every time I run into that case I tend to create constructor abominations with long parameter

9条回答
  •  庸人自扰
    2020-12-04 06:52

    In Scala 2.8, you could use named and default parameters as well as the copy method on a case class. Here's some example code:

    case class Person(name: String, age: Int, children: List[Person] = List()) {
      def addChild(p: Person) = copy(children = p :: this.children)
    }
    
    val parent = Person(name = "Bob", age = 55)
      .addChild(Person("Lisa", 23))
      .addChild(Person("Peter", 16))
    

提交回复
热议问题