EachWithIndex groovy语句
收藏

I am new to groovy and I've been facing some issues understanding the each{} and eachwithindex{} statements in groovy.

Are each and eachWithIndex actually methods? If so what are the arguments that they take?

groovy文档中有以下示例:

def numbers = [ 5, 7, 9, 12 ]
numbers.eachWithIndex{ num, idx -> println "$idx: $num" } //prints each index and number

Well, I see that numbers is an array. What are num and idx in the above statement? What does the -> operator do?

I do know that $idx and $num prints the value, but how is it that idx and num are automatically being associated with the index and contents of the array? What is the logic behind this? Please help.

最佳答案

These are plain methods but they follow quite a specific pattern - they take a Closure as their last argument. A Closure is a piece of functionality that you can pass around and call when applicable.

例如,方法eachWithIndex可能看起来像这样(大致):

void eachWithIndex(Closure operation) {
    for (int i = 0; this.hasNext(); i++) {
        operation(this.next(), i); // Here closure passed as parameter is being called
    }
}

这种方法允许构建通用算法(例如对项目进行迭代),并在运行时通过传递不同的闭包来更改具体的处理逻辑。

Regarding the parameters part, as you see in the example above we call the closure (operation) with two parameters - the current element and current index. This means that the eachWithIndex method expects to receive not just any closure but one which would accept these two parameters. From a syntax prospective one defines the parameters during closure definition like this:

{ elem, index ->
    // logic 
}

So -> is used to separate arguments part of closure definition from its logic. When a closure takes only one argument, its parameter definition can be omitted and then the parameter will be accessible within the closure's scope with the name it (implicit name for the first argument). For example:

[1,2,3].each {
    println it
} 

可以这样重写:

[1,2,3].each({ elem ->
    println elem
})

如您所见,Groovy语言添加了一些语法糖,使这种构造看起来更漂亮。

    公众号
    关注公众号订阅更多技术干货!