问题
I have a collection which I process with removeIf {}
in Groovy. Inside the block, I have access to some it
identifier. What is this and where is it documented?
回答1:
it
is an implicit variable that is provided in closures. It's available when the closure doesn't have an explicitly declared parameter.
When the closure is used with collection methods, such as removeIf
, it
will point to the current iteration item.
It's like you declared this:
List<Integer> integers = [1, 2, 3]
for(Integer it: integers) {print(it)}
When you use each
, instead (and that's an example), you can get it
implicitly provided:
integers.each{print(it)} //it is given by default
Or
integers.removeIf{it % 2 == 0} //it is the argument to Predicate.test()
it
will successively take the values 1
, 2
, and 3
as iterations go.
You can, of course, rename the variable by declaring the parameter in the closure:
integers.each{myInteger -> print(myInteger)}
In this case, Groovy doesn't supply the implicit it
variable. The documentation has more details
回答2:
If you create a closure without an explicit argument list, it defaults to having a single argument named it
. Here's an example that can be run in the Groovy console
Closure incrementBy4 = { it + 4 }
// test it
assert incrementBy4(6) == 10
In the example above the closure is identical to
Closure incrementBy4 = { it -> it + 4 }
Here's another example that uses removeIf
Closure remove2 = { it == 2 }
def numbers = [1, 2, 3]
numbers.removeIf(remove2)
// verify that it worked as expected
assert numbers == [1, 2]
来源:https://stackoverflow.com/questions/54902509/what-is-the-groovy-it