Reputation: 5487
We currently utilize the map based constructor in an @Immutable class and pass all field values during instantiation. I'd like to set sensible defaults for fields in case user doesn't supply any value for them during instantiation?
Is there a groovy way (an easy way) to do it?
Upvotes: 0
Views: 647
Reputation: 14529
You can fill in the attributes in the class declaration:
@groovy.transform.Immutable
class Person {
String name = 'john'
}
p = new Person(name: 'percy')
assert p.name == 'percy'
p2 = new Person()
assert p2.name == 'john'
Update: Groovy fails if any setters is used after creating the object.
try {
p2.name = 'echo'
assert p2.name == 'echo'
assert false
} catch(e) {
assert true
}
Update 2: Ah, groovyConsole
to the rescue. @Immutable
is setting the name
field in the constructor, thus, the field is, in fact, final.
Upvotes: 1