How does @Immutable work in groovy?

When I execute the code below in the groovy console, I get groovy.lang.ReadOnlyPropertyException . As expected, since the x property cannot be changed (since ClassA is immutable).

 import groovy.transform.Immutable @Immutable class ClassA { int x } def a = new ClassA(x: 5); ax = 1 

But if I change the access modifier to private for the variable x , then I can do this in the groovy console:

 import groovy.transform.Immutable @Immutable class ClassA { private int x } def a = new ClassA(x: 5); ax = 1 println(ax) 

Why is this? Why does the added private access modifier make ClassA mutable?

+6
source share
1 answer

docs have a clear position on this. They always talk about "properties." There are also excerpts indicating that "rolling your own" is not considered a "state":

You do not have to follow Groovy normal usage agreements, for example. you can create an explicit private field, and then you can write explicit get and set methods. This approach is not currently prohibited (to give you some room for maneuver to circumvent these conventions), but any fields created in this way are not considered part of the significant state of the object and are not considered equal or hashCode.

a trivial indicator for this is the fact that toString is created for such classes. eg:.

 @groovy.transform.Immutable class A { private int a } @groovy.transform.Immutable class B { int b } a=new A() aa = 42 println a b=new B() // bb = 42 println b 

will print:

 A() B(0) 

shows that A.@a not part of the “computation” for immutability (“significant state”). and since you can access private vars in groovy, your code above works just fine.

+8
source

Source: https://habr.com/ru/post/974669/


All Articles