Kotlin是否有“枚举"字样?像Python一样的功能?
问题描述:
在Python中,我可以写:
In Python I can write:
for i, element in enumerate(my_list):
print i # the index, starting from 0
print element # the list-element
我怎么用Kotlin来写这个?
How can I write this in Kotlin?
答
There is a forEachIndexed
function in the standard library:
myList.forEachIndexed { i, element ->
println(i)
println(element)
}
也请参见 @ s1m0nw1的答案,withIndex
也是迭代Iterable
的一种非常不错的方法
See @s1m0nw1's answer as well, withIndex
is also a really nice way to iterate through an Iterable
.