I am new to groovy and I\'ve been facing some issues understanding the each{}
and eachwithindex{}
statements in groovy.
Are each
a
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: