How to create an infinite loop in Kotlin

3 Answers

0 votes
// Infinite while (true) Loop

fun main() {
    var count = 0

    while (true) { // infinite loop
        println("Iteration: $count")

        if (count == 3) {
            println("Breaking out of loop...")
            break
        }

        count++
    }

    println("Loop finished.")
}



/*
run:

Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Breaking out of loop...
Loop finished.

*/

 



answered Apr 11 by avibootz
0 votes
// Infinite do { } while (true) Loop

fun main() {
    var count = 0

    do { // infinite loop
        println("Count: $count")

        if (count == 3) {
            println("Breaking out of loop...")
            break
        }

        count++
    } while (true) // infinite loop

    println("Finished.")
}



/*
run:

Count: 0
Count: 1
Count: 2
Count: 3
Breaking out of loop...
Finished.

*/

 



answered Apr 11 by avibootz
0 votes
// Infinite Loop Using generateSequence (Functional style)

fun main() {
    var count = 0
    
    /*
    enerateSequence(0) { it + 1 } creates an infinite sequence starting at 0.
    
    The seed (first value) is 0
    
    The next value is computed by the lambda:
    it + 1
    
    So the sequence becomes: 0, 1, 2, 3, 4, 5, 6, ...
    It never ends because there is no stopping condition.
    */
    generateSequence(0) { it + 1 }.forEach { // infinite loop
        println("Index: $count")

        if (count == 3) {
            println("Breaking out of loop...")
            return
        }

        count++
    }
}



/*
run:

Index: 0
Index: 1
Index: 2
Index: 3
Breaking out of loop...

*/

 



answered Apr 11 by avibootz
edited Apr 11 by avibootz
...