2

sometime based on some condition it may want to jump (or move forward) a few steps inside the for loop,

how to do it is kolin?

a simplified use case:

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
}

in Java it could be:

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;
   }
}

How to do it in kotlin?

for(i in array.indices){
  val processed = processData(i);
  // todo
}
2
  • 1
    There is always good old while... Commented Jun 4, 2018 at 15:10
  • I don't think it's a clean solution to change the counter variable manually, use while instead Commented Jun 4, 2018 at 15:10

2 Answers 2

6

With 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++
}
Sign up to request clarification or add additional context in comments.

1 Comment

use datArray.length insted of datArray.length - 1. Because this is lessThan only not lessThan and equalTo
0

You can do that with continue as stated in the Kotlin docs here: https://kotlinlang.org/docs/reference/returns.html

Example:

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

This would only print names longer than 4 characters (as it skips names with a length of 4 and below)

Edit: this only skips one iteration at a time. So if you want to skip multiple, you could store the process state somewhere else and check the status for each iteration.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.