Vita Rara: A Life Uncommon

Closures and Bindings in Groovy: Question

Great blog post about closure. But it reminds me that I red stuffs like this in "Groovy in Action". By the way, there is still something I don't get: the following programm

Vector myArray = new Vector()
int i = 0
0.upto(2) {
myArray.add( {println "Current i is:"+i} )
i++
}
for ( clos in myArray )
clos.call()

has the following output:
Current i is:3
Current i is:3
Current i is:3
and using the Binding you talk about:


Vector myArray = new Vector()

0.upto(2) {
def clos = {println "Current value is:" + this.it}
def binding = new Binding ()
binding.setVariable ("it", it)
clos.setBinding (binding)
myArray.add( clos )
}

for ( clos in myArray )
clos.call()

has the result:

Current value is:2
Current value is:2
Current value is:2

I don't get how to associate data to a closure...

Reply

Please solve the math problem above and type in the result. e.g. for 1+1, type 2
  • Allowed HTML tags: <a> <img> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <pre> <h1> <h2> <h3>
  • Lines and paragraphs break automatically.
More information about formatting options