Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of "shallowly immutable" in the documentation of Record in Java 14

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).

like image 904
Debapriya Biswas Avatar asked May 28 '20 04:05

Debapriya Biswas


People also ask

What does it mean when a class is immutable in Java?

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.

What does it mean for an object to be immutable Java?

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.

Is Java record immutable?

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.

Is record class immutable?

By definition a record class is shallowly immutable, carrier for a fixed set of values called as record components.


1 Answers

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.

like image 80
Alex R Avatar answered Sep 20 '22 12:09

Alex R