Home > Blockchain >  How to add a condition to a for loop in Kotlin?
How to add a condition to a for loop in Kotlin?

Time:02-11

I know that in Java, it is possible to do the following:

boolean condition = true;

for(int i=0; i<array.length && condition; i  ){

}

If the condition is false, the for loop stops, but, how to do the same in Kotlin?

CodePudding user response:

You can also use the below approach for the conditional for loop.

(0..array.length).takeWhile {
    condition
}.forEach {
    // do something with `it (index)`
}

CodePudding user response:

there is no such option in Kotlin (availabe constructions in HERE), but you can add additional check and break keyword

for (i in 0..array.length) {
    if (!condition) break; // quit loop without further iteration
    //rest of code
  • Related