6

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
  • 2
    There are no counter-based for loops in Kotlin. Just use while loop instead. Commented Feb 10, 2022 at 21:47
  • Have you consulted the documentation? kotlinlang.org/docs/control-flow.html, kotlinlang.org/docs/returns.html Commented Feb 10, 2022 at 21:51
  • 1
    What is that you need to do? Maybe there's a more idiomatic way to do it. E.g. array.takeWhile { condition }.forEach { } Commented Feb 10, 2022 at 22:38

3 Answers 3

3

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

(0..array.length).takeWhile {
    condition
}.forEach {
    // do something with `it (index)`
}
Sign up to request clarification or add additional context in comments.

3 Comments

That should be (0..<array.length), otherwise you'll get an IndexOutOfBoundsException for index = array.length. Better still, use array.indices.
It should be array.size rather array.length, correcting as I got confused when referring to this answer. for(i in 0..< array.size){}
Careful with this one! The condition is executed array.length times before the forEach.
2

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

1 Comment

for (i in 0..<array.length)
1
fun checkCondition(){
  val condition=true
  outerloop@for(i in array.indices) {
    if(array[i]!=condition){
      condition=false
      break@outerloop
    }
  }
  return condition
}

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.