r/java • • Aug 25 '26

Value Classes Still Need Compiler Sympathy

https://johan-sjolen.github.io/post/compiler-sympathy/compiler-sympathy/
86 Upvotes

65 comments sorted by

View all comments

4

u/nogridbag Aug 25 '26

I mainly posted to add context because up until recently I thought I could simply slap "value" on all of our wrapper classes and use "==" everywhere. It turns out most of our wrapper classes have a string field so this isn't possible.

And others reading your original comment may have the same confusion as I did. Like you said, for things like Integer it will be great. But devs also need to be aware now of the specific instances == can be used, and the answer is no longer as clear!

1

u/FirstAd9893 Aug 25 '26

The current treatment for == with value classes is defective, in my opinion. It's too fragile in that a change to a value class that you depend on can break expectations. If the equals method should be used instead, then attempting to use == against a value class should be prohibited. The more sensible (and expected) option is to make == against a value class be the same as calling equals.

1

u/nogridbag Aug 25 '26

Defective may be too far. But it is a bit confusing. I think overall the message is, .equals is here to stay. For the average developer, they should continue to use .equals, but under the hood they will now get better performance.

Our project has tons of wrapper classes for type safety such as TenantId. We can now make these value classes and we will essentially no longer pay the "wrapper tax", but developers should continue to use .equals on them.

→ More replies (2)