Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The for loop in Kotlin iterates over any object that provides an iterator. Unlike traditional C-style for loops that rely on initialization, condition, and increment expressions, Kotlin’s for loop operates exclusively as a “foreach” construct. It uses the in operator to traverse iterables, arrays, ranges, or any custom class that implements the required operator functions.
for (item in iterable) {
    // execution block
}
If the body of the loop contains only a single statement, the curly braces {} can be omitted.

Underlying Mechanism

Kotlin’s for loop relies on convention-based duck typing rather than requiring the implementation of a specific interface like kotlin.collections.Iterator. For an object to be evaluated on the right-hand side of the in keyword, it must satisfy the following compiler requirements via member or extension functions:
  1. It must provide an iterator() function that returns an object.
  2. The returned object must provide a next() function.
  3. The returned object must provide a hasNext() function returning a Boolean.
All three of these functions must be explicitly marked with the operator modifier.
// Conceptual translation of a Kotlin for loop by the compiler
val iterator = iterable.iterator()
while (iterator.hasNext()) {
    val item = iterator.next()
    // execution block
}

Ranges and Progressions

When iterating over primitive types, Kotlin avoids the overhead of allocating iterator objects. Iteration over ranges (IntRange, LongRange, CharRange) is compiled directly into optimized, index-based loops at the JVM level. Closed-ended Range (..): Iterates up to and including the upper bound.
for (i in 1..5) { }
Half-open Range (until / ..<): Iterates up to, but excluding, the upper bound.
for (i in 1 until 5) { }
// or
for (i in 1..<5) { }
Reverse Progression (downTo): Iterates in descending order.
for (i in 5 downTo 1) { }
Custom Step (step): Modifies the increment or decrement value of the progression. The step value must be strictly positive.
for (i in 1..10 step 2) { }
for (i in 10 downTo 1 step 3) { }

Array and Collection Iteration

Arrays and standard library collections natively implement the required iterator() operator. Iterating by Index: To iterate over an array or list using its indices without boxing overhead, use the indices property.
for (i in list.indices) {
    val element = list[i]
}
Destructuring Declarations: Kotlin supports destructuring within the for loop declaration. The withIndex() library function returns an Iterable of IndexedValue objects, which can be destructured directly into index and value components.
for ((index, value) in list.withIndex()) {
    // index is Int, value is the element type
}
Master Kotlin with Deep Grasping Methodology!Learn More