Kotlin Loops in Kotlin Looping over iterables


Example

You can loop over any iterable by using the standard for-loop:

val list = listOf("Hello", "World", "!")
for(str in list) {
    print(str)
}

Lots of things in Kotlin are iterable, like number ranges:

for(i in 0..9) {
    print(i)
}

If you need an index while iterating:

for((index, element) in iterable.withIndex()) {
    print("$element at index $index")
}

There is also a functional approach to iterating included in the standard library, without apparent language constructs, using the forEach function:

iterable.forEach {
    print(it.toString())
}

it in this example implicitly holds the current element, see Lambda Functions