Kotlin Loops in Kotlin Looping over iterables


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

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

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

for(i in 0..9) {

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 {

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