Does Kotlin have an “enumerate” function like Python?

Iterations in Kotlin: Some Alternatives

Like already said, forEachIndexed is a good way to iterate.

Alternative 1

The extension function withIndex, defined for Iterable types, can be used in for-each:

val ints = arrayListOf(1, 2, 3, 4, 5)

for ((i, e) in ints.withIndex()) {
    println("$i: $e")
}

Alternative 2

The extension property indices is available for Collection, Array etc., which let’s you iterate like in a common for loop as known from C, Java etc:

for(i in ints.indices){
     println("$i: ${ints[i]}")
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)