Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy nested closures with using 'it'

Tags:

Code inside closures can refer to it variable.

8.times { println it } 

or

def mywith(Closure closure) {    closure() }  mywith { println it } 

With this behavior in mind you can't expect following code to print 0011

2.times {    println it      mywith {       println it    } } 

And instead I have to write

2.times { i ->    println i      mywith {       println i    } } 

My question is: why closures without parameters override it variable even if they don't need it.

like image 998
Mykola Golubyev Avatar asked Mar 02 '10 08:03

Mykola Golubyev


1 Answers

If you define a closure like this

def closure = {println "i am a closure"} 

It appears to have no parameters, but actually it has one implicit parameter named it. This is confirmed by:

def closure = {println "i am a closure with arg $it"} closure("foo") 

which prints

"i am a closure with arg foo"

If you really want to define a closure that takes 0 parameters, use this:

def closure = {-> println "i am a closure"} 

Your example could therefore be rewritten as:

2.times {    println it      mywith {->       println it    } } 
like image 114
Dónal Avatar answered Oct 07 '22 13:10

Dónal