Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have just getters and not setter?

I am quite new to groovy, and I have found out that by making a field public, groovy provides getters and setters by default. Is there a way to have just the getters but not the setters by default? The reason behind this is that I have a Builder and I don't want to provide access to the object fields for modification.

like image 803
Tavo Avatar asked Feb 22 '15 12:02

Tavo


1 Answers

You can make the fields final and add the Canonical transform to get the c'tor created automatically for you. Or even easier use the Immutable transform:

@groovy.transform.Immutable
class A {
    String x
}

def a = new A("x")
assert a.x == "x"
// a.x = "will fail"
// a.setX("will fail")

In any case, you should take a look into the builder transforms, what they have to offer for your use case.

like image 70
cfrick Avatar answered Nov 15 '22 07:11

cfrick