5

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!

6
  • 3
    Why would you need an alternate way to do it other than while(true)? Commented Dec 12, 2020 at 15:56
  • @Tenfour04 just out of curiosity. Since I am new to kotlin I am studying referencing my prior knowledge I had in java. That's all. Commented Dec 12, 2020 at 16:01
  • 3
    while (true) is readable that is even used in pseudo codes, I don't think any confusing syntax is better. Commented Dec 12, 2020 at 17:05
  • @Tenfour04 because while (true) is ugly and I'm used to programming language with a more elegant form of the endless loop. Commented Dec 15, 2023 at 17:23
  • @Martin, out of curiosity, can you tell me what language that is? I’ve never encountered anything more elegant than while(true) in any of the languages I’ve learned. Commented Dec 15, 2023 at 21:01

2 Answers 2

7

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

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

}
Sign up to request clarification or add additional context in comments.

2 Comments

I got a warning Names _, __, ___, ..., are reserved in Kotlin in my IntelliJ IDEA 2020.3 then I replaced _ with i and worked well. Thought I was looking for an equivalent code for(;;){} but Thanks.
This is as close to equivalent as you can get in Kotlin. Kotlin for loops work exclusively with iterables.
2

You can get something like the loop keyword in rust with the following:

fun loop(action: () -> Unit) {
  while(true)
    action()
}

// To use
loop {
  println("Not going to stop!")
}

1 Comment

even better, make it an inline function with crossinline parameter

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.