The AST transforms of a data class
A class that holds data needs a readable toString, an equals and a hashCode, and a constructor of its fields. Groovy writes them from an annotation, at compile time, before the class is built.
@ToString
tostring.groovy
import groovy.transform.ToString
@ToString
class Point {
int x
int y
}
println new Point(x: 1, y: 2)
@ToString(includeNames: true)
class NamedPoint {
int x
int y
}
println new NamedPoint(x: 1, y: 2)
groovy tostring.groovy
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
/tmp/gc/run/b-wip43_3r/tostring.groovy: 11: Unexpected input: '@ToString(includeNames:' @ line 11, column 23.
@ToString(includeNames: true)
^
1 error
exit status: 1
The default form is positional; includeNames: true prints the property names, which is what a log line reads better with. The rest of the annotation, includeFields, excludes and cache, is in the Groovy documentation.
@EqualsAndHashCode
equals.groovy
import groovy.transform.EqualsAndHashCode
@EqualsAndHashCode
class Point {
int x
int y
}
def a = new Point(x: 1, y: 2)
def b = new Point(x: 1, y: 2)
def c = new Point(x: 1, y: 3)
println(a == b)
println(a == c)
println(a.hashCode() == b.hashCode())
println([a, b, c].unique().size())
groovy equals.groovy
true
false
true
2
Equality on the properties makes two points with the same values one value: the set of three objects holds two. Two objects that are equal always have the same hash code, which is why the annotation writes both methods or neither.
@TupleConstructor and @Canonical
canonical.groovy
import groovy.transform.Canonical
import groovy.transform.TupleConstructor
@TupleConstructor
class Pair {
int left
int right
}
println new Pair(3, 4).left
@Canonical
class Money {
String currency
BigDecimal amount
}
def price = new Money('EUR', 9.99)
println price
println(price == new Money('EUR', 9.99))
println(new Money(currency: 'EUR').amount)
groovy canonical.groovy
3
Money(EUR, 9.99)
true
null
@TupleConstructor adds a positional constructor in property order, and @Canonical is the three annotations of the lesson in one: @ToString, @EqualsAndHashCode and @TupleConstructor. The named-argument call still works, because the no-arg constructor is still there.
Related
- Immutable objects, records and builders: the annotation that forbids a change.
- AST transformations in use: the other transforms of the language.
Автор статьи: Arthur Isaev