Groovy Documentation

groovy.transform
[Java] Annotation Type Immutable

java.lang.Object
  groovy.transform.Immutable

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@GroovyASTTransformationClass("org.codehaus.groovy.transform.ImmutableASTTransformation")
public @interface Immutable

Class annotation used to assist in the creation of immutable classes.

It allows you to write classes in this shortened form:

 @Immutable class Customer {
     String first, last
     int age
     Date since
     Collection favItems
 }
 def d = new Date()
 def c1 = new Customer(first:'Tom', last:'Jones', age:21, since:d, favItems:['Books', 'Games'])
 def c2 = new Customer('Tom', 'Jones', 21, d, ['Books', 'Games'])
 assert c1 == c2
 
The @Immutable annotation instructs the compiler to execute an AST transformation which adds the necessary getters, constructors, equals, hashCode and other helper methods that are typically written when creating immutable classes with the defined properties.

A class created in this way has the following characteristics:

Immutable classes are particularly useful for functional and concurrent styles of programming and for use as key values within maps. If you want similar functionality to what this annotation provides but don't need immutability then consider using @Canonical.

Customising behaviour:

You can customise the toString() method provided for you by @Immutable by also adding the @ToString annotation to your class definition.

Limitations:

Authors:
Paul King
Andre Steingress
See Also:
ToString
Canonical
Since:
1.7


 
Optional Element Summary
java.lang.Class knownImmutableClasses

Allows you to provide @Immutable with a list of classes which are deemed immutable.

 
Method Summary
 
Methods inherited from class java.lang.Object
java.lang.Object#wait(long, int), java.lang.Object#wait(long), java.lang.Object#wait(), java.lang.Object#equals(java.lang.Object), java.lang.Object#toString(), java.lang.Object#hashCode(), java.lang.Object#getClass(), java.lang.Object#notify(), java.lang.Object#notifyAll()
 

Element Detail

knownImmutableClasses

public java.lang.Class[] knownImmutableClasses
Allows you to provide @Immutable with a list of classes which are deemed immutable. By supplying a class in this list, you are vouching for its immutability and @Immutable will do no further checks. Example:
 import groovy.transform.*
 @Immutable(knownImmutableClasses = [Address])
 class Person {
     String first, last
     Address address
 }

 @TupleConstructor
 class Address {
     final String street
 }
 
@default {}
Since:
1.8.7


 

Groovy Documentation