Groovy 的“它”是什么?

2023-12-24

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


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

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

就像你这样声明的:

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

当你使用each,相反(这是一个例子),你可以得到it隐式提供:

integers.each{print(it)} //it is given by default

Or

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

it将依次取值1, 2, and 3随着迭代的进行。

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

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

在这种情况下,Groovy 不提供隐式it多变的。文档 http://groovy-lang.org/closures.html#implicit-it有更多详细信息

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Groovy 的“它”是什么? 的相关文章

随机推荐