I am new to groovy and I\'ve been facing some issues understanding the each{}
and eachwithindex{}
statements in groovy.
Are each
a
Normally, if you are using a functional programing language such as Groovy, you would want to avoid using each
and eachWithIndex
since they encourage you to modify state within the closure or do things that have side effects.
If possible, you may want to do your operations using other groovy collection methods such as .collect
or .inject
or findResult
etc.
However, to use these for your problem, i.e print the list elements with their index, you will need to use the withIndex
method on the original collection which will transform the collection to a collection of pairs of [element, index]
For example,
println(['a', 'b', 'c'].withIndex())