Search code examples
for-loopkotlinwhile-loopinfinite-loop

Infinite loop in kotlin using for loop?


In java we can write infinite loop using both while and for

for(;;){
  // doesn't stop[infinite loop] 
}

and using while

while(true){
  // doesn't stop[infinite loop] 
}

the syntax for kotlin's while loop for creating infinite loop is the same.

How do I create an infinite loop using for loop just like the example I wrote above(equivalent code) using kotlin.

Thank you!


Solution

  • There's no easy syntax, but you could generate an infinite sequence with generateSequence:

    for (i in generateSequence(0) { it }) {
    
    }