Previously I'd thought that a property in Groovy is indicated by the omission of a scoping keyword. In other words
class Test {
def prop = "i am a property"
public notProp = "i am not"
}
However, it appears I'm incorrect about this, because the following script prints "getter val"
class Foo {
public bar = "init val"
public getBar() {
"getter val"
}
}
println new Foo().bar
The fact that the getter is invoked when bar
is accessed suggests that bar
is a property rather than a field. So what exactly is the difference between fields and properties in Groovy.
Thanks, Don
The def keyword is used to define an untyped variable or a function in Groovy, as it is an optionally-typed language.
In Groovy, as in any other Object-Oriented language, there is the concept of classes and objects to represent the objected oriented nature of the programming language. A Groovy class is a collection of data and the methods that operate on that data.
Variables in Groovy can be defined in two ways − using the native syntax for the data type or the next is by using the def keyword. For variable definitions it is mandatory to either provide a type name explicitly or to use "def" in replacement. This is required by the Groovy parser.
" this " in a block mean in Groovy always (be it a normal Java-like block or a Closure) the surrounding class (instance). " owner " is a property of the Closure and points to the embedding object, which is either a class (instance), and then then same as " this ", or another Closure.
In order to access a field directly you have to prepend it with an @ sign:
assert "getter val" == new Foo().bar
assert "init val" == new Foo().@bar
That the short form of new Foo().getBar()
works, although bar
is not a property, is still concise from my point of view.
In contrast you can't make a call to foo.setBar("setter val")
, but you could in case you would have defined bar
as a property without the access modifier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With