Java Reference
In-Depth Information
Figure 4.6. The
@Immutable
AST transformation results in an immutable object that can be used in both Java
and Groovy clients.
The
@Immutable
transformation can only be applied to Groovy classes, but those classes
can then be used in Java applications. I'll start by showing how the @
Immutable
annota-
tion works and what its limitations are, and then use an immutable object in a Java class.
Here's an immutable point class. It contains two fields,
x
and
y
, which represent the loca-
tion of the point in a two-dimensional space:
@Immutable
class
ImmutablePoint {
double
x
double
y
String toString() { "($x,$y)" }
}
The @
Immutable
annotation is applied to the class itself. It still allows the properties
to be set through a constructor, but once set the properties can no longer be modified. The
next listing shows a Spock test to demonstrate that fact.