forEachIndexed

public inline fun <T> Iterable<T>.forEachIndexed(
action: (index: Int, T) -> Unit): Unit {
    var index = 0
    for (item in this) action(index++, item)
}

val list = listOf(1, 2, 3, 4, 5)
list.forEachIndexed{ index, value ->
    println("index = $index, value = $value")
}

/*
index = 0, value = 1
index = 1, value = 2
index = 2, value = 3
index = 3, value = 4
index = 4, value = 5
*/

Last updated