it是闭包中提供的隐式变量。当闭包没有显式声明的参数时可用。
当闭包与集合方法(例如)一起使用时removeIf,it将指向当前迭代项。
就像您这样声明:
List<Integer> integers = [1, 2, 3]
for(Integer it: integers) {print(it)}
Run Code Online (Sandbox Code Playgroud)
当使用each代替时(这是一个示例),可以it隐式提供:
integers.each{print(it)} //it is given by default
Run Code Online (Sandbox Code Playgroud)
要么
integers.removeIf{it % 2 == 0} //it is the argument to Predicate.test()
Run Code Online (Sandbox Code Playgroud)
it将陆续取值1,2和3作为迭代去。
当然,您可以通过在闭包中声明参数来重命名变量:
integers.each{myInteger -> print(myInteger)}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,Groovy不提供隐式it变量。该文档有更多详细信息
如果你创建一个没有显式参数列表的闭包,它默认有一个名为it. 这是一个可以在 Groovy 控制台中运行的示例
Closure incrementBy4 = { it + 4 }
// test it
assert incrementBy4(6) == 10
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,闭包等同于
Closure incrementBy4 = { it -> it + 4 }
Run Code Online (Sandbox Code Playgroud)
这是另一个使用的示例 removeIf
Closure remove2 = { it == 2 }
def numbers = [1, 2, 3]
numbers.removeIf(remove2)
// verify that it worked as expected
assert numbers == [1, 2]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1556 次 |
| 最近记录: |