groovy

Strange behavior on property setter

Details

  • Type: Bug Bug
  • Status: Closed Closed
  • Priority: Minor Minor
  • Resolution: Fixed
  • Affects Version/s: 1.0-JSR-3
  • Fix Version/s: 1.5.2
  • Component/s: None
  • Labels:
    None
  • Environment:
    Groovy jsr-03, java version "1.5.0_05", winXP
  • Number of attachments :
    0

Description

Try this:

class Foo {
  private _xxx

  public void setBar(b) {
    println "before setting"
    _xxx = b
    println "after setting"  
  }
}

def x = new Foo()

x.bar = 1
x.bar = 2

When run, the output is:

C:\Temp>groovy settertest.groovy
before setting
after setting
before setting
after setting
Caught: groovy.lang.GroovyRuntimeException: Cannot read property: bar

even though the property bar was never read. If you add e.g.
println "goodbye"
as the last line of the script, the exception does not occur.

Issue Links

Activity

Hide
blackdrag blackdrag added a comment -

this is a well known issue.
imagine:

def foo() {
x
}

x is returned here

your example is put into a method by groovy. This means x.bar=2 is transformed into:
x.bar=2
return x.bar

so it's no wonder that you will get this error message

Show
blackdrag blackdrag added a comment - this is a well known issue. imagine: def foo() { x } x is returned here your example is put into a method by groovy. This means x.bar=2 is transformed into: x.bar=2 return x.bar so it's no wonder that you will get this error message
Hide
Peter Niederwieser added a comment -

The transformation "x.bar = 2; return x.bar" is incorrect.¹ Instead it should be "return (x.bar = 2)", which would solve this issue.

¹ It's even more likely to have unwanted side-effects when a method is involved, for example in "x.bar().foo = 2".

Show
Peter Niederwieser added a comment - The transformation "x.bar = 2; return x.bar" is incorrect.¹ Instead it should be "return (x.bar = 2)", which would solve this issue. ¹ It's even more likely to have unwanted side-effects when a method is involved, for example in "x.bar().foo = 2".
Hide
Andres Almiray added a comment -

FYI this bug is still around.

Show
Andres Almiray added a comment - FYI this bug is still around.
Hide
Paul King added a comment -

This was fixed with GROOVY-2244. In fact I think this was a duplcate issue.

Show
Paul King added a comment - This was fixed with GROOVY-2244. In fact I think this was a duplcate issue.
Hide
Paul King added a comment -

close off release 1.5.4

Show
Paul King added a comment - close off release 1.5.4

People

Vote (1)
Watch (1)

Dates

  • Created:
    Updated:
    Resolved: