Given an object with properties and a constructor, I wish to copy the constructor arguments into properties, and then do some additional work in the Constructor.
import groovy.transform.TupleConstructor
@TupleConstructor
class Thing{
def one
def two
public Thing(one, two){
doSomething()
}
def doSomething(){
println "doing something with one : $one and two: $two"
}
}
println new Thing(1, 2).dump()
This will successfully copy the args to the properties if I do nothing else in the constructor, but if I call “doSomething()” in the constructor, the properties are not copied.
I’m seeking “The Groovy” Way for copying args to properties.
As tim_yates mentioned, the TupleConstructor AST transformation won’t do anything if you have another constructor defined (you can blame this line of code =P). If you need to run some other code in the construction of the object, you may add that in a static factory method and use that instead of the tuple constructor directly:
Notice that i’m using a variable-argument static method to receive an arbitrary number of parameters and then calling the tuple constructor with those parameters (used the “spread” (
*) operator for that).Unfortunately, the TupleConstructor AST transform does not seem to have an option for adding the tuple constructor as private, which would be useful in this case.