Groovy property definition

I used to think that a property in Groovy is indicated by the absence of the scoping keyword. In other words

class Test { def prop = "i am a property" public notProp = "i am not" } 

However, it seems I'm wrong 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 getter is called when bar accessed suggests that bar is a property, not a field. So, what is the difference between fields and properties in Groovy.

Thanks Don

+6
groovy
source share
4 answers

To access the field directly, you need to add it using the @ sign:

 assert "getter val" == new Foo().bar assert "init val" == new Foo() .@bar 

That the short form new Foo().getBar() , although bar not a property, is still concise from my point of view.

In contrast, you cannot make a call to foo.setBar("setter val") , but you could if you defined bar as a property without an access modifier.

+3
source share

You are looking for a difference that is not in groovy.

In Groovy, fields and properties were combined to make them act and look the same.

+1
source share

Using a modifier really suppresses property creation. What confuses you is that . it seems that he refuses access to the field when such a property does not exist.

  $ groovysh
 Groovy Shell (2.1.0, JVM: 1.7.0_21)
 Type 'help' or '\ h' for help.
 -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- ----------------------------
 groovy: 000> class A {def a = "foo"};
 ===> true
 groovy: 000> new A (). getA ()
 ===> foo
 groovy: 000> new A (). a
 ===> foo
 groovy: 000> new A (). properties
 ===> {class = class A, a = foo}

But:

  groovy: 000> class A {public def a = "foo"};
 ===> true
 groovy: 000> new A (). getA ()
 ERROR groovy.lang.MissingMethodException:
 No signature of method: A.getA () is applicable for argument types: () values: []
 Possible solutions: getAt (java.lang.String), grep (), grep (java.lang.Object), with (groovy.lang.Closure), putAt (java.lang.String, java.lang.Object), wait ()
         at groovysh_evaluate.run (groovysh_evaluate: 2)
         ...
 groovy: 000> new A (). a
 ===> foo
 groovy: 000> new A (). properties
 ===> {class = class A}
+1
source share

I think @ Christoph Metsendorf's answer was right ...

To access the field directly, you need to add it using the @ sign:

 assert "getter val" == new Foo().bar assert "init val" == new Foo() .@bar 

... but I would add that in your Foo example, your getBar method overrides the getBar method that Groovy created for you. You can use the above syntax to directly access bar if you want to continue to override the default getBar method of Groovy generated for you, or you simply cannot override getBar so that any getBar call uses the Groovy getter created for you.

0
source share

All Articles