3 ms·
It's such a shame that value classes in Valhalla can only be immutable... C# has mutable value based classes since years and this enable major optimizations in
by The_rationalist 5y ago
It's such a shame that value classes in Valhalla can only be immutable...
C# has mutable value based classes since years and this enable major optimizations in much more common use cases. This is also what everybody do in C.
In addition to being less expressive and programmable, it should also be slower, e.g you have a value class that has ten fields, you just want to update one and ineptly, you have to reconstruct the whole object and reassign/copy every fields that have not changed..
Regarding ergonomics, they are totally broken, e.g you can't have an idiomatic Point.
You cannot write point.x = 5
- ygra 5y agoMutable value types in C# have a place, but they also come with plenty of pitfalls. Java tends to lean in a direction where those don't exist. Cf. captured variables in closures as well: having to treat them as final avoids a number of problems.
- kaba0 5y agoWhile to my knowledge there is not yet a final decision, ‘withers’ are planned to solve that. https://github.com/openjdk/amber-docs/blob/master/eg-drafts/reconstruction-records-and-classes.md https://github.com/openjdk/amber-docs/blob/master/eg-drafts/... Basically, p = p with { .x = 3 } or something like that. But that will also planned to work for other kind of classes and will be a basis for advanced pattern matching as well. Also, in case of a primitive class with no guarantee of non-tearing, in practice you will get the same performance as with a mutable struct, maybe even better as the JVM can better reason about it.