Search code examples
groovyexpando

groovy Expando : why it consider the local variable and not the expando properties?


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


Solution

  • 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.