我只是 kotlin 的新手,并开始通过它解决问题。但有一件事让我很困惑如何做到这一点!
for(int i = 0, j = arr.length - 1; i < arr.length - 1; i++, j--){
//do something
}
如何在 kotlin 中一次运行两个 for 循环,就像上面用 java 完成的代码片段一样。
我只是 kotlin 的新手,并开始通过它解决问题。但有一件事让我很困惑如何做到这一点!
for(int i = 0, j = arr.length - 1; i < arr.length - 1; i++, j--){
//do something
}
如何在 kotlin 中一次运行两个 for 循环,就像上面用 java 完成的代码片段一样。
您可以使用带有倒排索引的单循环
var j = 0
for(i in arr.indices){
j = arr.lastIndex - i
//i will go from 0 to lastindex
//j will go from lastindex to 0
}
或使用zip
for ((i, j) in arr.indices.zip(arr.indices.reversed())){
//i will go from 0 to lastindex
//j will go from lastindex to 0
}
像这样的东西
for ( (i, j) in (0..6).zip(6 downTo 0)){
//do stuff
}