This is my simple groovy script;
def fourtify(String str) {
def clsr = {
str*4
}
return clsr
}
def c = fourtify("aa")
println("binding variables: ${c.getBinding().getVariables()}")
...
All I'm trying to do here is being able to access the free variable "str" using the closure instance to understand how closure works behind the scenes a bit more better. Like, perhaps, Python's locals() method.
Is there a way to do this?
The closure you have defined does not store anything in
bindingobject - it simply returns String passed asstrvariable, repeated 4 times.This
bindingobject stores all variables that were defined without specifying their types or usingdefkeyword. It is done via Groovy metaprogramming feature (getPropertyandsetPropertymethods to be more specific). So when you define a variableslike:then this closure will create a binding with key
sand value evaluated from expressionstr * 4. This binding object is nothing else than a map that is accessed viagetPropertyandsetPropertymethod. So when Groovy executess = str * 4it callssetProperty('s', str * 4)because variable/propertysis not defined. If we make a slightly simple change like:then binding
swon't be created, becausesetPropertymethod does not get executed.Another comment to your example. If you want to see anything in binding object, you need to call returned closure. In example you have shown above the closure gets returned, but it never gets called. If you do:
then your closure gets called and binding object will contain bindings (if any set). Now, if you modify your example to something like this:
you will see following output in return:
Hope it helps.