Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy property definition

Tags:

groovy

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

like image 987
Dónal Avatar asked Sep 23 '09 14:09

Dónal


People also ask

What def means in Groovy?

The def keyword is used to define an untyped variable or a function in Groovy, as it is an optionally-typed language.

What is a Groovy object?

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.

What is a Groovy variable?

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.

What is this in Groovy?

" 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.


1 Answers

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.

like image 155
Christoph Metzendorf Avatar answered Oct 06 '22 21:10

Christoph Metzendorf