phani phani - 1 year ago 71
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?

Answer Source

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'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download