Search⌘ K
AI Features

Modernizing Iteration Practices

Explore modern iteration methods in Kotlin, including for loops with indices, indexed values using withIndex, and forEachIndexed. Understand how to efficiently iterate over collections and maps to write cleaner and more idiomatic Kotlin code.

Explicit index iteration

Developers with experience in older languages often use a for loop where slightly more modern alternatives should be used instead.

Kotlin 1.5
fun main() {
val names = listOf("Alex", "Bob", "Celina")
for (i in 0 until names.size) {
val name = names[i]
println("[$i] $name")
}
}
// [0] Alex
// [1] Bob
// [2] Celina
...