kotlin,如何动态改变 for 循环速度

lan*_*nyf 1 for-loop kotlin

有时基于某些条件,它可能想要在 for 循环内跳转(或向前移动)几步,

kolin 怎么办?

一个简化的用例:

val datArray  = arrayOf(1, 2, 3......)

/**
 * start from the index to process some data, return how many data has been 
   consumed
*/
fun processData_1(startIndex: Int) : Int  {
   // process dataArray starting from the index of startIndex
   // return the data it has processed
}
fun processData_2(startIndex: Int) : Int  {
   // process dataArray starting from the index of startIndex
   // return the data it has processed
}
Run Code Online (Sandbox Code Playgroud)

在 Java 中,它可能是:

for (int i=0; i<datArray.lenght-1; i++) {
   int processed = processData_1(i);
   i += processed; // jump a few steps for those have been processed, then start 2nd process
   if (i<datArray.lenght-1) { 
       processed = processData_2(i);
       i += processed;
   }
}
Run Code Online (Sandbox Code Playgroud)

如何在 kotlin 中做到这一点?

for(i in array.indices){
  val processed = processData(i);
  // todo
}
Run Code Online (Sandbox Code Playgroud)

s1m*_*nw1 5

while

var i = 0

while (i < datArray.length - 1) {
    var processed = processData_1(i)
    i += processed // jump a few steps for those have been processed, then start 2nd process
    if (i < datArray.length - 1) {
        processed = processData_2(i)
        i += processed
    }
    i++
}
Run Code Online (Sandbox Code Playgroud)