1

looking at this test code:

def a = "test"

def expando = new Expando()

expando.a = a

expando.foobar = {a}

expando.a = "test1"

assert expando.foobar() != a

why the last assertion fail? it considers "a" as the local variable and not as the expando.a properties.

Thanks for help

res1
  • 3,482
  • 5
  • 29
  • 50

1 Answers1

3

Perhaps I am mistaken, but when you invoke expando.foobar(), it returns the result of the closure that was assigned to foobar. In this case, it is a, so it returns the value of a: test.

expando.foobar() does not call the property 'a' because closures do not look for their delegate unless a variable is not defined in scope (and in this case it is).

Edit: If you were to do expando.foobar = {delegate.a}, that would return the results you are expecting.

Igor
  • 33,276
  • 14
  • 79
  • 112
  • @GrailsGui I agree with you, when i assign the closure to foobar it use the value of "a", but when i execute the foobar() method it is referred to the expando class so i was thinking it will look at the "a" property of the expando class, the scope in this case is the expando class, but i see i am wrong. i was thiking the expando class like a class A { def a def foobar(){ a } } – res1 Jul 17 '11 at 20:35
  • That is the case! It's just that the 'a' in the closure is the local variable. I updated my explanation. – Igor Jul 17 '11 at 21:29