groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Paul King <pa...@asert.com.au>
Subject Re: Closure does not see field when setting value
Date Tue, 08 Nov 2016 12:43:19 GMT
Jochen, indeed the Closure version goes through setProperty() but I
thought we made it work in methods:

import groovy.transform.Field

@Field
int x = 2

def a() {
    assert x == 2
    println x
    x = 1
    assert x == 1
    println x
}

println x
binding.variables.remove('x')
a()
assert x == 1
println x
println binding.variables.x

but not closures?

Cheers, Paul.


On Tue, Nov 8, 2016 at 10:04 PM, Jochen Theodorou <blackdrag@gmx.org> wrote:
>
>
> On 08.11.2016 12:19, Paul King wrote:
>>
>> I think that is probably a bug - but with reads and writes.
>
>
> not sure it is really a bug. @Field in a script may give the script a field,
> but it will also have:
>
>>     public Object getProperty(String property) {
>>         try {
>>             return binding.getVariable(property);
>>         } catch (MissingPropertyException e) {
>>             return super.getProperty(property);
>>         }
>>     }
>>
>>     public void setProperty(String property, Object newValue) {
>>         if ("binding".equals(property))
>>             setBinding((Binding) newValue);
>>         else if("metaClass".equals(property))
>>             setMetaClass((MetaClass)newValue);
>>         else
>>             binding.setVariable(property, newValue);
>>     }
>
>
> So reading "x" in the open block will go through getProperty, where it will
> first try the binding and failing there use the "normal" getProperty which
> will deliver him the field value. Writing "x" will go through setProperty
> and there it will write into the binding, giving the field no chance.
>
> The intended usage of @Field was for an open block, to give it additional
> state, it just does not work as expected in a Script, unless you change the
> get/setProperty implementations or use a different base class
>
> bye Jochen

Mime
View raw message