Posts Tagged ‘mop’

Something surprising in Groovy Meta Programing

2011/01/10

Suppose you have a Groovy shell which contains the following code:

def b = 5
println this.binding.getVariable("b")

If you run this script, an error is reported:

Caught: groovy.lang.MissingPropertyException: No such property: b for class: groovy.lang.Binding

But if you remove the “def” type of variable b, surprise, it works!

def b = 5
println this.binding.getVariable("b")

This means that a variable of a script is stored in its binding only when the variable is not declared with a type. Interesting, no?

The reason for this strange behavior is that when in a script a variable is not declared, it is then stored in the binding of the script. If the variable is not yet contained in the binding, then it is added to the binding. On the other side, when a variable is declared in the script, then it is considered local, and not stored in the binding.

I don’t really undestand the reason of this rule, though. It only complicates things unnecessarity. Simply putting everything in the binding would be clear and leave the programmer no chance to make mistakes (in confusing binding or not binding).

Exploring the Groovy literatur to find more …