迭代:Kotlin是否有像Python一样的“枚举”function?

在Python中,我可以写:

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

我怎样才能在Kotlin写这个?

标准库中有一个forEachIndexed函数:

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

另请参阅@ s1m0nw1的答案 ,使用withIndex也是迭代Iterable一个非常好的方法。

Kotlin中的迭代:一些选择

  1. 就像已经说过的, forEachIndexed是一个办法。

  2. 我想指出一个替代方案,在Iterabletypes上的可扩展的withIndex可以用于withIndex

     val ints = arrayListOf(1, 2, 3, 4, 5) for ((i, e) in ints.withIndex()) { println("$i: $e") } 
  3. 然后在CollectionArray等等上有一个扩展属性indices ,这些indices接近于从C,Java等已知的通用属性:

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