I have this code in Groovy:
class Person {
def age
Person () {
println age // null
}
}
def p = new Person ([age: '29'])
println p.age // 29
I need to read age value in constructor, but it isn’t setted yet.
How can I do this?
Note: I don’t want to use a init() method and call manually every time, like
class Person {
def age
def init() {
println age // now have 29
}
}
def p = new Person ([age: '29'])
p.init()
println p.age // 29
Link to GroovyConsole.
Thanks!
You can write a constructor like this:
If you’re using groovy 1.8, take a look at the
@TupleConstructorannotation, which will automatically build a constructor like the one above, as well as a list based one.