What is the Groovy 'it'?

故事扮演 提交于 2020-08-25 04:40:27

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!