迭代: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中的迭代:一些选择
-
就像已经说过的,
forEachIndexed
是一个办法。 -
我想指出一个替代方案,在
Iterable
types上的可扩展的withIndex
可以用于withIndex
:val ints = arrayListOf(1, 2, 3, 4, 5) for ((i, e) in ints.withIndex()) { println("$i: $e") }
-
然后在
Collection
,Array
等等上有一个扩展属性indices
,这些indices
接近于从C,Java等已知的通用属性:for(i in ints.indices){ println("$i: ${ints[i]}") }
- 如何在Kotlin的嵌套Hashmap迭代中使用`filterValues`?
- 我如何设置FlexBox.alignItems以编程方式flex_end?
- javascript匿名对象在kotlin
- 编译的kt文件是由字节码组成的?
- 为什么我可以在Kotlin的DayForecast(HashMap(it))之前插入一个行代码?
- 从Long到ByteArray的两次转换有什么区别?
- yield在Maven项目的buildSequence中抛出KotlinNullPointerException
- Android Kotlin Gson缓慢的Json反序列化
- RecyclerView.Adapter-错误:公共函数在Kotlin中公开它的内部返回类型