如何在Groovy的eachWithIndex方法中指定索引的起始值?

ubi*_*con 2 groovy closures loops

当使用Groovy的eachWithIndex方法时,索引值从0开始,我需要从1开始.我该怎么做?

tim*_*tes 8

索引将始终从 0

你的选择是:

1)向索引添加偏移量:

int offs = 1
list.eachWithIndex { it, idx ->
  println "$it @ pos ${idx + offs}"
}
Run Code Online (Sandbox Code Playgroud)

2)使用除以外的东西eachWithIndex(即:将原始列表中从1开始的整数列表转置,然后循环执行此操作)

3)你也可以使用默认参数来破解这种事情......如果我们传递eachWithIndex一个带有3个参数的闭包(两个eachWithIndex期望值和第三个参数的默认值index + 1):

[ 'a', 'b', 'c' ].eachWithIndex { item, index, indexPlusOne = index + 1 ->
  println "Element $item has position $indexPlusOne"
}
Run Code Online (Sandbox Code Playgroud)

我们将给出输出:

Element a has position 1
Element b has position 2
Element c has position 3
Run Code Online (Sandbox Code Playgroud)