How to add a condition to a for loop in Kotlin?

Viewed 1092

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?

3 Answers

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

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

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
fun checkCondition(){
  val condition=true
  outerloop@for(i in array.indices) {
    if(array[i]!=condition){
      condition=false
      break@outerloop
    }
  }
  return condition
}
Related