phani phani - 4 months ago 7
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

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'
Comments