Java Record "shallowly immutable"
In the documentation of Java Records there's the term "shallowly immutable". What do we mean by shallowly immutable?
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.
An example for the "shallowly immutability" could be a record instance having an ArrayList instance as its field. While that record field cannot refer to any other ArrayList list instance, the list's elements can still change (by code holding a reference to that list instance contained in the record). Because the list instance remains mutable even though it's now contained in an immutable record instance – you will only ever get "shallow immutability" from a record.
An immutable record
This is record is an immutable object. Since it is a record, it is automatically final and has no setters. All is good.
A mutable record
This time the record is a mutable because of List().
The problem is that records use shallow immutability.
Making the record actually be immutable
It’s pretty easy to make the record actually be mutable. In fact, it only requires three extra lines! Records have a compact constructor which takes care of the setting fields for you. However, you can choose to change that behavior.
Now the test program fails with an UnsupportedOperationException. Much better. A real immutable record.
Comments
Post a Comment