For 循环 kotlin(10)

    For 循环
for 循环可以对任何提供迭代器(iterator) 的对象进行遍历,语法如下:
for (item in collection) print(item)
循环体可以是一个代码块。
for (item: Int in ints) {
      // ……
}
如上所述, for 可以循环遍历任何提供了迭代器的对象。即:
有一个成员函数或者扩展函数 iterator() ,它的返回类型
有一个成员函数或者扩展函数 next() ,并且
有一个成员函数或者扩展函数 hasNext() 返回 Boolean 。
这三个函数都需要标记为 operator 。
对数组的 for 循环会被编译为并不创建迭代器的基于索引的循环。
如果你想要通过索引遍历一个数组或者一个 list,你可以这么做:
for (i in array.indices) {
print(array[i])
}
控制流
注意这种“在区间上遍历”会编译成优化的实现而不会创建额外对象。
或者你可以用库函数 withIndex :
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
原文地址:https://www.cnblogs.com/mamamia/p/8385450.html