This strategy is used with the @Builder) AST transform to create a builder helper class
for the fluent and type-safe creation of instances of a specified class.
You define classes which use this builder pattern as follows:
import groovy.transform.builder.*
import groovy.transform.*
{@code @ToString}
{@code @Builder}(builderStrategy=InitializerStrategy) class Person {
String firstName
String lastName
int age
}
While it isn't required to do so, the benefit of this builder strategy comes in conjunction with static compilation. Typical usage is as follows:
{@code @CompileStatic}
def method() {
println new Person(Person.createInitializer().firstName("John").lastName("Smith").age(21))
}
which prints:
Person(John, Smith, 21)
If you don't initialise some of the properties, your code won't compile, e.g. if the method body above was changed to this:
println new Person(Person.createInitializer().firstName("John").lastName("Smith"))
then the following compile-time error would result:
[Static type checking] - Cannot find matching method Person#(Person$PersonInitializer ). Please check if the declared type is right and if the method exists.
The message is a little cryptic, but it is basically the static compiler telling us that the third parameter, {@code age} in our case, is unset.