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?
You can also use the below approach for the conditional for loop.
(0..array.length).takeWhile {
condition
}.forEach {
// do something with `it (index)`
}
(0..<array.length), otherwise you'll get an IndexOutOfBoundsException for index = array.length. Better still, use array.indices.for(i in 0..< array.size){}condition is executed array.length times before the forEach.
forloops in Kotlin. Just usewhileloop instead.array.takeWhile { condition }.forEach { }