Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 38 ยท Classes and Traits

AST Transformations and Annotations

Cut boilerplate with Groovy AST transformations: @ToString, @EqualsAndHashCode, @TupleConstructor, @Immutable, @Builder, @Lazy, @Memoized, @Delegate, @Singleton, @Sortable and records.

Writing toString, equals, hashCode, constructors and builders by hand is repetitive and error-prone. Groovy removes that work with AST transformations: annotations that change your class while it is being compiled. The compiler reads your annotated class, generates the missing methods, and the result is ordinary bytecode, with no run-time cost and no reflection.

This lesson tours the transformations you will use most. Groovy code is read-only on this site, so each group of annotations is paired with a runnable Java version showing what gets generated.

How it works

The compiler turns source code into an Abstract Syntax Tree (AST), a tree of nodes that represents classes, methods and statements. A transformation is a small program that edits the tree before bytecode is produced. For example @ToString adds a toString() method node to your class. You never see the generated source, but you can call the method.

flowchart LR
    A["Source with @ToString"] --> B["Parse to AST"]
    B --> C["Transformation adds toString()"]
    C --> D["Bytecode"]
    D --> E["Normal class with toString()"]

The annotation is processed at compile time, so the finished class is as fast as hand-written code.

All of these live in the package groovy.transform (and groovy.transform.builder for builders), so import them first.

@ToString

GROOVY
import groovy.transform.ToString

@ToString
class Person {
    String name
    int age
}

println new Person(name: 'Ada', age: 36)       // Person(Ada, 36)

Useful options:

GROOVY
@ToString(includeNames = true, excludes = ['password'], includePackage = false)
class Account {
    String user
    String password
}
println new Account(user: 'ada', password: 'x')    // Account(user:ada)

includeNames prints name:value, excludes hides sensitive fields, includeSuper adds the parent's fields and ignoreNulls omits null values.

@EqualsAndHashCode

GROOVY
import groovy.transform.EqualsAndHashCode

@EqualsAndHashCode
class Point {
    int x, y
}

assert new Point(x: 1, y: 2) == new Point(x: 1, y: 2)
def set = [new Point(x: 1, y: 2)] as Set
assert new Point(x: 1, y: 2) in set

It generates equals and hashCode from the properties (use includes or excludes to choose). Two equal objects have equal hash codes, so they behave in sets and as map keys.

@TupleConstructor and @MapConstructor

@TupleConstructor creates a positional constructor, and @MapConstructor a constructor that takes a map (useful when you also declared other constructors):

GROOVY
import groovy.transform.*

@TupleConstructor
@MapConstructor
class Item {
    String sku
    int qty = 1
}

def a = new Item('A-1')
def b = new Item('B-2', 5)
def c = new Item(sku: 'C-3', qty: 2)

@Canonical

@Canonical combines @ToString, @EqualsAndHashCode and @TupleConstructor in one annotation. It was the most popular shortcut for value classes for many years, and you will see it in a lot of existing code. Many teams now list the individual annotations for clarity, or use @Immutable or a record when the object should not change.

GROOVY
import groovy.transform.Canonical

@Canonical
class Money {
    BigDecimal amount
    String currency = 'EUR'
}

println new Money(10.5)                  // Money(10.5, EUR)
assert new Money(1) == new Money(1)
Java Java stand-in: the code @Canonical writes for you

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

@Immutable

@Immutable makes a class that cannot change after construction: all properties become final, there are no setters, collections are wrapped read-only and toString, equals, hashCode and constructors are generated.

GROOVY
import groovy.transform.Immutable

@Immutable
class Coordinate {
    double lat
    double lon
}

def c = new Coordinate(lat: 51.5, lon: -0.12)
// c.lat = 0     // ReadOnlyPropertyException
println c

Immutable objects are safe to share between threads and make good map keys. When you need a "changed copy", construct a new object (or use @AutoClone/a copy method).

Groovy 4 and later also understands Java-style record declarations: record Point(int x, int y) { } gives you an immutable data carrier with the usual methods, interoperating with Java records.

Java Java: a record is Java's version of @Immutable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

@Builder

GROOVY
import groovy.transform.builder.Builder

@Builder
class Pizza {
    String size
    List toppings = []
    boolean extraCheese
}

def pizza = Pizza.builder()
    .size('large')
    .toppings(['ham', 'olives'])
    .extraCheese(true)
    .build()
println pizza.size               // large

@Builder supports several strategies (SimpleStrategy, ExternalStrategy, InitializerStrategy) with different styles of chaining. Use it when a class has many optional values.

@Lazy

@Lazy delays creating an expensive field until first use, safely:

GROOVY
class Report {
    @Lazy List data = loadData()

    private List loadData() {
        println 'loading...'
        [1, 2, 3]
    }
}

def r = new Report()
println 'created'
println r.data      // prints "loading..." then [1, 2, 3]
println r.data      // no second load

With @Lazy(soft = true), the value can be garbage collected when memory is short and recreated later.

@Memoized

@Memoized on a method caches the result per argument list:

GROOVY
import groovy.transform.Memoized

class Calc {
    @Memoized
    long fib(int n) { n < 2 ? n : fib(n - 1) + fib(n - 2) }
}
println new Calc().fib(50)       // 12586269025, fast thanks to the cache

Only use it on methods that depend purely on their arguments.

@Delegate

@Delegate forwards all public methods of a field to the field's object, so you can compose behavior without inheriting:

GROOVY
import groovy.transform.*

class AuditedList {
    @Delegate List items = []         // gains add, size, get, each ...
    int changes = 0

    boolean add(Object o) {
        changes++
        items.add(o)
    }
}

def l = new AuditedList()
l.add('a'); l.add('b')
println "${l.size()} items, $l.changes changes"      // 2 items, 2 changes

Methods you define yourself win over the delegated ones, so you can override just what you need.

@Singleton, @Sortable, @InheritConstructors

GROOVY
import groovy.transform.*

@Singleton
class Registry {
    Map entries = [:]
}
Registry.instance.entries.a = 1

@Sortable(includes = ['last', 'first'])
class Name {
    String first, last
}
println([new Name(first: 'B', last: 'Z'), new Name(first: 'A', last: 'Z')].sort()*.first)   // [A, B]

@InheritConstructors
class MyError extends RuntimeException { }
  • @Singleton creates a single instance accessible by .instance, with an optional lazy mode.
  • @Sortable implements Comparable plus comparators for each property.
  • @InheritConstructors copies the parent's constructors, handy for custom exceptions.

Logging and others

@Log, @Slf4j, @Log4j2 add a logger field named log; @AutoClone and @AutoImplement generate clone and stub methods; @Synchronized, @WithReadLock and @WithWriteLock add locking. @TypeChecked and @CompileStatic (see Variables and Typing) are also AST transformations.

Choosing the right annotation

Need Use
Readable printing @ToString
Value equality @EqualsAndHashCode
Value class in one line @Canonical or @Immutable
Many optional parameters @Builder
Expensive field @Lazy
Cache a pure method @Memoized
Forward methods to a field @Delegate
One shared instance @Singleton

What next

You have covered the core language: syntax, collections, closures and classes. The rest of the course builds on it with metaprogramming (changing classes at run time), builders and DSLs, testing with Spock and the build ecosystem. Return to the track overview any time to see the full chapter list.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does an AST transformation such as @ToString run?

    Transformations edit the abstract syntax tree during compilation, so the generated methods are normal bytecode.
  2. 2. What does @Immutable do to properties?

    @Immutable creates a class whose state cannot change after construction.
  3. 3. Which annotation delays creating a field until it is first read?

    @Lazy initialises the field on first access, once.
  4. 4. What does @Delegate on a field do?

    It adds methods to the class that forward to the field's object, so you can compose behavior.

Summary

  • AST transformations are compile-time annotations that generate code in groovy.transform.
  • @ToString, @EqualsAndHashCode, @TupleConstructor and @Canonical remove value-class boilerplate; @Immutable and records make safe value objects.
  • @Builder gives fluent construction; @Lazy and @Memoized add safe laziness and caching.
  • @Delegate, @Singleton, @Sortable and @InheritConstructors cover composition and common patterns.

Next: The MetaClass and Dynamic Dispatch in Groovy