AST transformations in use
An AST transformation rewrites the class before the compiler writes bytecode. The annotations of the previous chapter are transforms, and so are the four here. Groovy 5 moved several of them from groovy.transform to groovy.lang, and the default import of groovy.lang means they need no import line at all.
@Lazy and @Memoized
lazy.groovy
import groovy.transform.Memoized
class Config {
@Lazy String loaded = {
println 'loading once'
'configuration'
}()
int calls = 0
@Memoized
int slowSquare(int n) {
calls++
n * n
}
}
def config = new Config()
println config.loaded
println config.loaded
println config.slowSquare(4)
println config.slowSquare(4)
println config.calls
groovy lazy.groovy
loading once
configuration
configuration
16
16
1
A @Lazy field runs its initializer on the first read and keeps the value, so "loading once" appears once. @Memoized caches the result of the method per argument list, and the counter proves the body ran once for 4.
@Singleton
singleton.groovy
@Singleton
class Registry {
int count = 0
}
def first = Registry.instance
def second = Registry.instance
first.count = 3
println first.is(second)
println second.count
println Registry.instance.count
groovy singleton.groovy
true
3
3
The annotation writes a private constructor, a static field and an instance property, and a call of the constructor fails. Two reads of instance return the same object, so a write through one is visible through the other.
@AnnotationCollector
collector.groovy
import groovy.transform.AnnotationCollector
import groovy.transform.EqualsAndHashCode
import groovy.transform.ToString
@AnnotationCollector([ToString, EqualsAndHashCode])
@interface Value {
}
@Value
class Money {
String currency
BigDecimal amount
}
def money = new Money(currency: 'EUR', amount: 1)
println money
println(money == new Money(currency: 'EUR', amount: 1))
groovy collector.groovy
Money(EUR, 1)
true
@Value is a local annotation that stands for two of the library, which is how a project gives its own name to a convention. The collected annotation keeps the meaning of every member, and the named-argument constructor is still there because neither of the two replaces it.
Related
- The AST transforms of a data class: the three annotations this lesson collects.
- @CompileStatic and @TypeChecked: the transforms that change how a call is compiled.
Автор статьи: Arthur Isaev