EachWithIndex groovy statement

后端 未结 4 750
[愿得一人]
[愿得一人] 2021-02-02 08:03

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

Are each a

4条回答
  •  半阙折子戏
    2021-02-02 08:49

    each and eachWithIndex are, amongst many others, taking so called Closure as an argument. The closure is just a piece of Groovy code wrapped in {} braces. In the code with array:

    def numbers = [ 5, 7, 9, 12 ]
    numbers.eachWithIndex{ num, idx -> println "$idx: $num" }
    

    there is only one argument (closure, or more precisely: function), please note that in Groovy () braces are sometime optional. num and idx are just an optional aliases for closure (function) arguments, when we need just one argument, this is equivalent (it is implicit name of the first closure argument, very convenient):

    def numbers = [ 5, 7, 9, 12 ]
    numbers.each {println "$it" }
    

    References:

    • http://groovy.codehaus.org/Closures
    • http://en.wikipedia.org/wiki/First-class_function

提交回复
热议问题