Groovy中的'it'是什么?

18

我有一个集合,在Groovy中使用removeIf {}进行处理。在块内,我可以访问一些it标识符。这是什么,它在哪里记录?


2
http://groovy-lang.org/closures.html#implicit-it - doelleri
2个回答

28

it是闭包提供的隐式变量。当闭包没有显式声明参数时,它就可用。

当闭包与集合方法一起使用时,例如removeIfit将指向当前迭代项。

这就像你声明了这个:

List<Integer> integers = [1, 2, 3]
for(Integer it: integers) {print(it)}

当你使用each(这只是一个例子)时,它会被隐式提供。
integers.each{print(it)} //it is given by default

或者

integers.removeIf{it % 2 == 0} //it is the argument to Predicate.test()

it将会随着迭代而依次取值为123

当然,你也可以通过在闭包中声明参数来重命名变量:

integers.each{myInteger -> print(myInteger)}

在这种情况下,Groovy不提供隐式的it变量。文档有更多细节。

1
关于“它”,没有任何与迭代集合有关的特定内容。 - Dónal
@Dónal同意,我刚读完答案,意识到需要编辑。谢谢 - ernest_k
“Iterator”是一种指向集合中实际项的指针,用于在循环迭代期间进行迭代。 - xxxvodnikxxx

8
如果您创建了一个没有显式参数列表的闭包,它默认有一个名为it的单一参数。下面是一个在Groovy控制台中可以运行的示例。
Closure incrementBy4 = { it + 4 }

// test it
assert incrementBy4(6) == 10

在上面的例子中,闭包与…相同。
Closure incrementBy4 = { it -> it + 4 }

以下是使用removeIf的另一个示例:

Closure remove2 = { it == 2 }

def numbers = [1, 2, 3]
numbers.removeIf(remove2)

// verify that it worked as expected
assert numbers == [1, 2] 

为了更好地回答这个问题:{} 有隐式变量 "it"。{x->} 没有隐式的 "it" 变量,但有一个显式的 "x"。{->} 没有隐式的 "it" 变量和显式的变量。 - blackdrag

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接