Mastering Kotlin Loops: From Basic to Advanced

One of the many reasons Kotlin has become beloved by developers is its simplicity and clarity, particularly when it comes to loops. In this guide, we’ll journey from the basics to advanced use cases of Kotlin loops, offering clear examples at every stage.

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” – Martin Fowler


Basic Loops: The For Loop

In Kotlin, ‘for’ loop is used to iterate through anything that provides an iterator. Here’s a basic example:

fun main() {
    for (i in 1..5) {
        println(i) // prints 1 through 5
    }
}

In this example, the loop iterates over a range from 1 to 5 and prints out each number.


Iterating Over Collections

You can use the ‘for’ loop to iterate over collections such as lists and arrays:

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5)

    for (i in numbers) {
        println(i) // prints 1 through 5
    }
}

Intermediate Loops: While and Do-While Loops

While and do-while loops in Kotlin are used to iteratively execute a block of code as long as a condition is true.

While Loop

fun main() {
    var i = 1
    while (i <= 5) {
        println(i) // prints 1 through 5
        i++
    }
}

The while loop checks the condition before entering the loop. If the condition is true, it executes the block of code.

Do-While Loop

fun main() {
    var i = 1
    do {
        println(i) // prints 1 through 5
        i++
    } while (i <= 5)
}

The do-while loop is similar to the while loop, but the condition is evaluated after the execution of the block of code. This ensures that the loop will be executed at least once.


Advanced Loops: Nested and Labeled Loops

Nested and labeled loops offer greater control and complexity in your Kotlin code.

Nested Loop

A nested loop is a loop within a loop. The inner loop executes its entire cycle for each iteration of the outer loop.

fun main() {
    for (i in 1..3) {
        for (j in 1..3) {
            println("i = $i , j = $j")
        }
    }
}

Labeled Loop

In Kotlin, you can label a loop, and use that label in a break or continue statement.

fun main() {
    outer@ for (i in 1..3) {
        for (j in 1..3) {
            if (i == 2 && j == 2) 
                break@outer
            println("i = $i , j = $j")
        }
    }
}

In this example, the break statement with the outer label terminates the labeled (outer) loop instead of the inner loop.

Understanding and mastering loops is essential in becoming proficient in Kotlin. They provide the means to efficiently process data, perform repetitive tasks, and manage the flow of your program. Remember, the road to mastery is a path of continuous learning. Keep practicing and exploring the limitless possibilities with Kotlin.

Share