kotlin,如何动态改变for循环节奏

时间:2018-06-04 15:07:26

标签: 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
}
在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;
   }
}

如何在kotlin中做到这一点?

for(i in array.indices){
  val processed = processData(i);
  // todo
}

2 个答案:

答案 0 :(得分:4)

使用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++
}

答案 1 :(得分:0)

您可以按照此处Kotlin文档中的说明continue执行此操作:https://kotlinlang.org/docs/reference/returns.html

示例:

val names = arrayOf("james", "john", "jim", "jacob", "johan")
for (name in names) {
    if(name.length <= 4) continue
    println(name)
}

这只会打印超过4个字符的名称(因为它会跳过长度为4及以下的名称)

编辑:这一次只跳过一次迭代。因此,如果要跳过多个,可以将进程状态存储在其他位置,并检查每次迭代的状态。