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.
I think it has something to do with the formal Closure definition of Groovy:
That means that a Groovy Closure will always have at least one argument, called it (if not specified otherwise) and it will be null if not given as a parameter.
The second example uses the scope of the enclosing closure instead.