Groovy annotations: @TupleConstructor
If you use an inversion-of-control/dependency injection container like PicoContainer that favors constructor injection, you might have classes that look like this:
class Foo {
Guh guh
Keks keks
Blorb blorb
Foo(Guh guh, Keks keks, Blorb blorb) {
this.guh = guh
this.keks = keks
this.blorb = blorb
}
}
Notice the constructor only sets fields? Why should you have to write this glue code yourself?
Fortunately, since 1.8.0, Groovy has a @TupleConstructor annotation that removes the need for a constructor.
@TupleConstructor
class Foo {
Guh guh
Keks keks
Blorb blorb
}
Behind the scenes, Groovy will add an empty constructor, as well as n new constructors, where n is the number of fields in the class. For the Foo class above, Groovy would add
class Foo {
Foo() {}
Foo(Guh guh) { … }
Foo(Guh guh, Keks keks) { … }
Foo(Guh guh, Keks keks, Blorb blorb) { … }
}
So, the next time you come across constructors that merely set some fields, replace them with @TupleConstructor.
