I am reading the documentation of Records and don't understand the term "shallowly immutable". What do we mean by shallowly immutable? And if it's immutable why we need a copy constructor? Why two "Hello Worlds!"?
For all record classes, the following invariant must hold: if a record R's components are c1, c2, ... cn, then if a record instance is copied as follows:
R copy = new R(r.c1(), r.c2(), ..., r.cn()); // copy constructor ?
then it must be the case that r.equals(copy)
.
In Java, when we create an object of an immutable class, we cannot change its value. For example, String is an immutable class. Hence, we cannot change the content of a string once created.
An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code.
Records are immutable data classes that require only the type and name of fields. The equals, hashCode, and toString methods, as well as the private, final fields and public constructor, are generated by the Java compiler.
By definition a record class is shallowly immutable, carrier for a fixed set of values called as record components.
Shallowly immutable means, that if a class has fields, these fields are treated as being final
. However, their fields (i.e. the fields of the fields) don't need to be final
.
You don't need to implement a constructor, it's already implemented this way for you. But if you choose to implement it yourself, e.g. for argument validation, then this invariant should hold.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With