0
0
KotlinHow-ToBeginner · 3 min read

How to Iterate Over Array in Kotlin: Simple Syntax and Examples

In Kotlin, you can iterate over an array using a for loop with syntax like for (item in array). You can also use forEach function to run a block of code for each element in the array.
📐

Syntax

To loop through an array in Kotlin, use the for loop with the syntax for (item in array). Here, item is each element in the array during each loop cycle.

Alternatively, use the forEach function which takes a lambda expression to process each element.

kotlin
val array = arrayOf("apple", "banana", "cherry")

// Using for loop
for (item in array) {
    println(item)
}

// Using forEach function
array.forEach { item ->
    println(item)
}
Output
apple banana cherry apple banana cherry
💻

Example

This example shows how to iterate over an array of numbers and print each number multiplied by 2.

kotlin
fun main() {
    val numbers = arrayOf(1, 2, 3, 4, 5)
    for (num in numbers) {
        println(num * 2)
    }
}
Output
2 4 6 8 10
⚠️

Common Pitfalls

One common mistake is trying to use a traditional C-style for loop with an index without accessing the array element properly.

Also, modifying the array while iterating can cause unexpected behavior.

kotlin
val array = arrayOf("a", "b", "c")

// Wrong: printing index instead of element
for (i in array.indices) {
    println(i) // prints 0, 1, 2 instead of elements
}

// Right: access element by index
for (i in array.indices) {
    println(array[i])
}
Output
0 1 2 a b c
📊

Quick Reference

MethodSyntaxDescription
For loopfor (item in array) { ... }Simple and readable way to iterate elements.
forEacharray.forEach { item -> ... }Functional style iteration with lambda.
Indexed for loopfor (i in array.indices) { array[i] }Access elements by index.

Key Takeaways

Use the simple for loop with 'for (item in array)' to iterate over arrays in Kotlin.
The forEach function offers a clean, functional way to process each element.
Avoid printing indices directly; access elements by index if needed.
Do not modify the array while iterating to prevent unexpected results.