Kotlin for Loop

Kotlin for loop offers a versatile and expressive way to iterate through collections, ranges, arrays, and strings. Unlike traditional for loops in other languages like Java, Kotlin’s for loop is more concise and powerful, making it a favorite among developers. In this guide, we’ll explore the syntax, real-world examples, and output of Kotlin’s for loop to help you master this essential feature.

Syntax of Kotlin’s For Loop

The syntax of Kotlin’s for loop is straightforward and flexible:

for (item in collection) {
    // Body of the loop
}

Here, item represents the current element in the collection being iterated.

Example 1: Iterating Through a Range

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

Output:

1
2
3
4
5

In this example, the loop iterates through the range from 1 to 5 inclusively and prints each value.

Example 2: Iterating Through an Array

fun main() {
    val languages = arrayOf("Ruby", "JavaScript", "Python", "Java")
    for (language in languages) {
        println(language)
    }
}

Output:

Ruby
JavaScript
Python
Java

Here, the loop iterates through each element of the languages array and prints each language.

Example 3: Iterating Through a String

fun main() {
    val text = "Kotlin"
    for (letter in text) {
        println(letter)
    }
}

Output:

K
o
t
l
i
n

This loop iterates through each character in the string text and prints each letter.

Example 4: Using Indices with Arrays

fun main() {
    val languages = arrayOf("Ruby", "Kotlin", "Python", "Java")
    for (index in languages.indices) {
        if (index % 2 == 0) {
            println(languages[index])
        }
    }
}

Output:

Ruby
Python

Here, we iterate through the indices of the languages array and print elements at even indices only.

Real-World Example: Filtering and Processing Data:

Consider a scenario where you have a list of numbers and you want to filter out the even numbers and print their squares:

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    for (number in numbers) {
        if (number % 2 == 0) {
            val square = number * number
            println("Square of $number is $square")
        }
    }
}

Output:

Square of 2 is 4
Square of 4 is 16
Square of 6 is 36
Square of 8 is 64
Square of 10 is 100

In this example, we iterate through the numbers list, filter out even numbers, compute their squares, and print the results.

Kotlin's for loop is a powerful tool for iterating through collections, ranges, arrays, and strings. Its concise syntax and flexibility make it easy to work with various data structures and perform complex operations efficiently. By mastering Kotlin's for loop, you can enhance your programming skills and write cleaner, more expressive code.