Does Kotlin have an “enumerate” function like Python?

痴心易碎 提交于 2019-11-29 05:47:00

There is a forEachIndexed function in the standard library:

myList.forEachIndexed { i, element ->
    println(i)
    println(element)
}

See @s1m0nw1's answer as well, withIndex is also a really nice way to iterate through an Iterable.

Iterations in Kotlin: Some Alternatives

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

  2. Alternative 1: the extension 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")
    }
    
  3. Alternative 2: 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]}")
    }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!