You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Groovy中的‘it’是什么?removeIf{}块中it的定义及文档查询

Great question! Let me break down everything you need to know about Groovy's it identifier, especially since you encountered it while using removeIf{}.

What is it in Groovy?

Core Definition & Meaning

it is Groovy's implicit closure parameter. When you write a closure (the code inside {} passed to methods like removeIf, each, or find) without explicitly declaring any parameters, Groovy automatically provides this default parameter name to represent the single value being passed into the closure at runtime.

In your removeIf{} example, it refers to each individual element in the collection as the method iterates through it. For instance:

def fruits = ["apple", "banana", "cherry", "date"]
fruits.removeIf { it.length() > 5 } // Removes "banana" and "cherry"

Here, it is each string element in the fruits list, and we're checking its length to decide whether to remove it.

When is it accessible?

  • it only exists when your closure has no explicitly declared parameters. If you define a parameter name yourself, it won't be available—you'll have to use the name you chose:
    fruits.each { fruit -> println fruit } // Uses "fruit" instead of "it"
    
  • This works for any closure that expects a single input parameter, which is why it's so common in collection operations like filtering, iterating, or transforming elements.

Official Documentation Context

Groovy's official language specification explicitly covers this implicit parameter behavior. In the Closures section of the spec, it states that when a closure omits its parameter list, Groovy automatically creates a single parameter named it for the closure. This feature is designed to make single-parameter closure syntax more concise and readable.

内容的提问来源于stack exchange,提问作者TMOTTM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:07:19