Kotlin是否有"枚举"功能像Python?

时间:2017-10-19 08:36:05

标签: list kotlin enumerate

在Python中我可以写:

for i, element in enumerate(my_list):
    print i          # the index, starting from 0
    print element    # the list-element

我怎么能在Kotlin写这个?

2 个答案:

答案 0 :(得分:21)

标准库中有forEachIndexed函数:

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

同样请参阅@s1m0nw1's answerwithIndex也是一种非常好的方法来迭代Iterable

答案 1 :(得分:18)

Kotlin中的迭代:一些替代方案

  1. BasicDBObjectBuilder一样,forEachIndexed是一种很好的迭代方式。

  2. 备选方案1:为withIndex类型定义的扩展程序Iterable可以在for中使用 - 每个:

    val ints = arrayListOf(1, 2, 3, 4, 5)
    
    for ((i, e) in ints.withIndex()) {
        println("$i: $e")
    }
    
  3. 备选方案2:扩展属性indices可用于CollectionArray等,这样您就可以在公共for循环中进行迭代C,Java等:

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