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.
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With