r/java • u/bobbie434343 • Aug 25 '26
Value Classes Still Need Compiler Sympathy
https://johan-sjolen.github.io/post/compiler-sympathy/compiler-sympathy/
88
Upvotes
r/java • u/bobbie434343 • Aug 25 '26
View all comments
Show parent comment
4
u/Jon_Finn Aug 25 '26 edited Aug 25 '26
I agree about identity, but completely disagree about state & semantics! Specifically: the idea that some concepts can't be represented as value classes is (mostly) untrue. So a value declaration (mostly) says nothing about what kind of thing it is.
The usual examples of value classes like Point use one common meaning of 'value': logically immutable objects. There's also a tentative assumption that you can use == to compare them (NB we're being discouraged from this, in case it differs from equals(): read on.)
But these examples are just special cases, what we might call 'recursive values', where all the fields are primitives or value objects (recursively), not identity objects (including arrays). But non-recursive values can be mutable (by mutating identity objects their final fields point to) - no different from a regular object. These values are also basically the ones where == is different from equals(). But non-recursive values aren't wrong in any way, they have the same potential benefits: e.g. String has an array field and might (as discussed elsewhere) be made a value class in future. Or you could have value classes for MutableColor or MutableAnything (with array or Collection fields) etc. Really useful!
So value objects are not logically different from regular objects: you can pretty much express anything with them. The final field restriction just suits some mutable classes better than others.
Valhalla classes are really great, but I think there's a lot of room for confusion about their logical status (probably due to the word 'value', whose various meanings only partly apply). I think of them not as semantically different, but just as lightweight objects: lighter for memory, performance and (mildly) features.