Reputation:
From the properties section of the Groovy documentation:
class Person {
String name
int age
}
You can define a property with:
an absent access modifier (no public, protected or private)
...
Groovy will then generate the getters/setters appropriately
So with the above code snippet, I can do this:
Person sveta = new Person("Sveta",22)
println(sveta.getname())
println(sveta.name)
Question: Why would you want to do this?
What is the purpose of declaring a variable with no access modifier and allowing the getter/setters
be generated for you automatically when I can still access the field directly, and circumvent the setter?
I'm not asking what the purpose of a setter is or why I would want to use one, what I'm asking is, Groovy generates the getter/setter
for you under certain circumstances, but in production when would you want to do this?
Upvotes: 0
Views: 182
Reputation: 1805
For me it is just a convenience for when you need to have a Java style bean object (for example to pass to a library or framework) with getters and setters and not to have to type and maintain all the getter and setter code / boilerplate. Also, when you access the field directly as in your example, it is still calling the getter and setter so the getters and setters in Groovy can provide custom functions or side effects (potentially not desirable) that are called even when direct field access is used. Like this:
import groovy.transform.ToString
@ToString
class Person {
String name
int age
String getName() {
if(name == 'fred') {
return 'fred bloggs'
}
else {
return name
}
}
}
def p = new Person()
p.name = 'fred'
assert p.name == 'fred bloggs'
assert p.getName() == 'fred bloggs'
println p.toString()
p.name = 'sally'
assert p.name == 'sally'
assert p.getName() == 'sally'
println p.toString()
Results in this output:
Person(fred bloggs, 0)
Person(sally, 0)
But you are right, I think the why of this needs to be more clearly explained in the Groovy documentation.
Upvotes: 1