3 ms·
Why not do what JS does? val emily2 = { ...emily1, age: 30 }; This has many advantages, one being that it provably and declaratively creates a copy, which i
by jeswin 7y ago
Why not do what JS does?
val emily2 = { ...emily1, age: 30 };
This has many advantages, one being that it provably and declaratively creates a copy, which is not the case with the builder. In fact the obsession with methods (and hence the implied state) is what makes Java a terrible misfit for functional paradigms such as immutability.
- riquito 7y agoJS is not any better in that regard, that simple example is ignoring nested objects, where the outer one is copied and the inner are referenced (unless you use triple dots all the way down - tedious and error prone, or even simply inefficient if done by some recursive algorithm). The syntax is cool though
- sa46 7y agoI don't understand what you mean by provably. The Java example does the exact same thing as the JS version: create a shallow clone with a different age. Do you mean the builder might do something different? // Java val emily2 = emily1.toBuilder().age(30).build() As far as adding the spread operator to Java, I think you'd have to require a Spreadable interface to use it or limit usage of the spread operators to records. It's not clear to me that the expressive power is worth it over a builder.
- jeswin 7y agoIf a tool analyzed the JS AST, it could conclude (with fairly trivial analysis) that emily2 is a shallow clone of emily1. No such guarantee is possible with the Java version.