phanin
phanin

Reputation: 5487

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?

Upvotes: 0

Views: 647

Answers (1)

Will
Will

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.

enter image description here

Upvotes: 1

Related Questions