tags:

views:

64

answers:

2

Hi,

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

+1  A: 

You're looking for a difference that isn't there in groovy.

"In Groovy, fields and properties have been merged so that they act and look the same."

Ted Naleid
A: 

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.

Christoph Metzendorf