phani phani - 6 months ago 19
Groovy Question

How to create an @Immutable Groovy class with default fallback values for fields?

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?


You can fill in the attributes in the class declaration:

class Person {
    String name = 'john'

p = new Person(name: 'percy')
assert == 'percy'

p2 = new Person()
assert == 'john'