3 ms·
Adding a new canonical constructor to all classes would very likely have backwards compatibility issues, so we'd likely need some sort of opt-in mechanism. In t
by papercrane 6y ago
Adding a new canonical constructor to all classes would very likely have backwards compatibility issues, so we'd likely need some sort of opt-in mechanism. In the end the language designers decided that they wanted to give developers a way to create a very focused kind of object.
This goes into the design motivations: https://cr.openjdk.java.net/~briangoetz/amber/datum.html https://cr.openjdk.java.net/~briangoetz/amber/datum.html
Additionally, one less talked about benefit of records is they have a simplified serialization scheme that is safer by default. Records when being deserialized have each of their members read and then the canonical constructor is called, if the values are not valid then the constructor can reject the fields instead of allowing an "impossible" object from being created.
- avodonosov 6y agoThe opt-in (or rather opt-out) could be a presence of user-defined constructor. The same way as with default no-arg constructor. Interesting note about serialization. That could also be part of the base class.