EachWithIndex groovy statement

后端 未结 4 692
[愿得一人]
[愿得一人] 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:43

    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())

提交回复
热议问题