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?


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.


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