Groovy – Create Immutable Objects

In Groovy, it is possible to directly create immutable objects using the groovy.transform.Immutable annotation. One possible use-case for – an object (with data initialized through the class constructor) that is passed to another application layer (e.g., service) but we don’t want that object modified in that layer.


The @Immutable annotation makes an immutable object. Its properties can be initialized using the constructor.

Class Constructor

To instantiate and initialize the object’s properties, use constructor with named parameters.


Let’s test out the class by instantiating it with values and modifying one of the properties.

Line 11 throws a ReadOnlyPropertyException.


Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert