6 ms·
I wonder about records - they would be great for simplified implementation of immutability, but they seem to not provide a way to copy with a subset of modified
by mateuszf 7y ago
I wonder about records - they would be great for simplified implementation of immutability, but they seem to not provide a way to copy with a subset of modified fields - like in Scala:
case class Person (
firstName: String,
lastName: String,
age: Int
)
you could create an instance like this:
val emily1 = Person("Emily", "Maness", 25)
and then create a new instance by updating several parameters at once, like this:
// emily is married, and a year older
val emily2 = emily1.copy(lastName = "Wells", age = 26)
- tadfisher 7y agoJava lacks default arguments for functions, which makes that particular API infeasible without adding support for such. They could generate "withFoo" methods or even builder types, but that would butt up against developer preference, so it's probably best to leave it up to developers or a third-party library. Kotlin has a very similar feature in its data classes, FWIW.
- skissane 7y ago> Java lacks default arguments for functions, which makes that particular API infeasible without adding support for such I really wish Java would add both default arguments for functions, and also support for passing function arguments by name. One of these days...
- nine_k 7y agoThis goes against the very idea of method signatures in Java an overloads based on them. An attempt to add it will likely bring in way, way more backwards-compatibility pain than any benefits are worth. Writing simple methods with few arguments helps.
- diegof79 7y agoYou can have named parameters and backward compatibility with method signatures, Groovy does that [1]. Ok, it cheats a little bit because named params are actually a syntax sugar for Maps. But other languages do the same (e.g. Python) and is very useful too. And if you can type check the map (as in Typescript) the functionality is equivalent to named params. [1] http://docs.groovy-lang.org/latest/html/documentation/#_named_parameters http://docs.groovy-lang.org/latest/html/documentation/#_name...
- viraptor 7y agoPython has real keyword parameters, not just a syntax sugar. They're just presented as a dict when you want to see them all. And you can splat that dict when calling. Ruby before 2.7 has a syntax sugar where keyword parameters are the same as a trailing hash. But that's changing as well.
- thu2111 7y agoThe JVM has all the machinery required to do this right, though: invokedynamic. Kotlin provides named arguments and a copy method on data classes/records that uses them. You do indeed have binary compatibility issues with them, but it's not a fundamental problem. It's just that it sits at the intersection of: - Problems that only affect library writers, rarely a high priority for language designers (Java being a exception) - Obscure JVM knowledge and new techniques - Poor Android JVM holding back the ecosystem by discouraging any bytecode techniques that post-date Java circa 2010.
- lmm 7y agoDoes Kotlin have anything to let you treat data classes in a generic way like you can do with Shapeless in Scala? That's where the real power comes IME - e.g. look at Circe where you can derive JSON encoders/decoders for arbitrarily nested case classes at compile time, so you have zero boilerplate but still get compile-time type safety that stops you from accidentally trying to serialise a file handle or semaphore.
- nitrogen 7y agoThere is the currently experimental kotlinx.serialization library that generates e.g. JSON codecs at compile time. Not sure if that fits the bill.
- lmm 7y agoLooks like it's doing annotation processing at compile time? The trouble with that is that you end up with "magic" code like calling methods that don't appear to exist, and in order to be able to work on the serialisation itself (e.g. to add a new format) you have to understand the "magic", because there isn't a good intermediate abstraction. The great advantage of Shapeless is that all the "magic" is in the library itself and it spits out a generic representation of your data classes in record form; you can implement a new serialisation format in 100% vanilla Scala without having to worry about any macros or annotations or anything.
- thu2111 7y agoIt's not annotation processing, it's a compiler plugin with IDE support. So pretty deeply integrated. It avoids some of those issues. The kotlinx.serialisation design is pretty nice. It's basically what you describe. The compiler generates generic code that can call into a variety of "codecs" but they don't have to actually be serialisation specific. So there are codecs for JSON, protobufs, CBOR etc but you can also do arbitrary object graph transformations with the framework. A deep clone being a simple hello-world type example. I've never used Shapeless but it sounds pretty similar in some ways. https://github.com/Kotlin/kotlinx.serialization https://github.com/Kotlin/kotlinx.serialization
- mrlala 7y ago>val emily1 = Person("Emily", "Maness", 25) The assumption of inputs based on the order of the class items frightens me!
- lmm 7y agoYou can use named parameters if you're worried: val emily1 = Person(firstName="Emily", lastName="Maness", age=25) Scala's approach to constructors is a good example of convention over configuration; in Java 99.9% of classes have a constructor like: this.firstName = firstName; this.lastName = lastName; this.age = age; which is just ceremonial boilerplate that obscures the actual logic of what the class is doing (an IDE can generate the constructor for you, but the person maintaining your code still has to take the time to comprehend it). You can do the more complicated things in cases where you need to, but it's important to keep the simple case simple.
- nine_k 7y agoLombok solves this for Java.
- Benjammer 7y agoYou'd probably have to manually write a Builder in the Person record class. Then the callsite might look something like this: val emily2 = emily1.newBuilder() .lastName("Wells") .age(26) .build() I think the inner Builder pattern is common enough in immutable java object implementations that they might want to include that fully in the Record class generation at some point. Most immutable object libraries that I've seen include a lot more functionality than Records, like builders.
- jeswin 7y agoWhy 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.
- on_and_off 7y agokotlin has this too .. but java does not have named params. It would be a good addition imo (think Rect(left, top, ....) , especially associated with default params. Alternatively, they could automatically generate a builder class for records. As always in java, I guess that somebody will duct tape an annotation based solution on top of the language to solve this.
- namelosw 7y agoIt is very cumbersome to not having the 'copy' or equivalence so that a lot of functional languages have similar things: F#: let updated = { old with prop = newValue } Elixir: update = %{ old | prop: newValue } Even JavaScript have similar stuff: const update = { ...old, prop: newValue }
- capableweb 7y agoClojure: (assoc old :key new-value) just a fn in the end