For 循环
for循环可以对任何提供迭代器(iterator)的对象进行遍历,这相当于像 C# 这样的语言中的foreach循环。for的语法如下所示:
for (item in collection) print(item)
for循环体可以是一个代码块。
for (item: Int in ints) {
// ……
}
如上所述,for可以循环遍历任何提供了迭代器的对象。这意味着:
有一个成员函数或者扩展函数iterator()返回Iterator<>:有一个成员函数或者扩展函数next()
有一个成员函数或者扩展函数hasNext()返回Boolean。
这三个函数都需要标记为operator。
如需在数字区间上迭代,请使用区间表达式:
fun main() {
//sampleStart
for (i in 1..3) {
println(i)
}
for (i in 6 downTo 0 step 2) {
println(i)
}
//sampleEnd
}
对区间或者数组的for循环会被编译为并不创建迭代器的基于索引的循环。
如果你想要通过索引遍历一个数组或者一个 list,你可以这么做:
fun main() {
val array = arrayOf("a", "b", "c")
//sampleStart
for (i in array.indices) {
println(array[i])
}
//sampleEnd
}
或者你可以用库函数withIndex:
fun main() {
val array = arrayOf("a", "b", "c")
//sampleStart
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
//sampleEnd
}
for循环可以对任何提供迭代器(iterator)的对象进行遍历,这相当于像 C# 这样的语言中的foreach循环。for的语法如下所示:
for (item in collection) print(item)
for循环体可以是一个代码块。
for (item: Int in ints) {
// ……
}
如上所述,for可以循环遍历任何提供了迭代器的对象。这意味着:
有一个成员函数或者扩展函数iterator()返回Iterator<>:有一个成员函数或者扩展函数next()
有一个成员函数或者扩展函数hasNext()返回Boolean。
这三个函数都需要标记为operator。
如需在数字区间上迭代,请使用区间表达式:
fun main() {
//sampleStart
for (i in 1..3) {
println(i)
}
for (i in 6 downTo 0 step 2) {
println(i)
}
//sampleEnd
}
对区间或者数组的for循环会被编译为并不创建迭代器的基于索引的循环。
如果你想要通过索引遍历一个数组或者一个 list,你可以这么做:
fun main() {
val array = arrayOf("a", "b", "c")
//sampleStart
for (i in array.indices) {
println(array[i])
}
//sampleEnd
}
或者你可以用库函数withIndex:
fun main() {
val array = arrayOf("a", "b", "c")
//sampleStart
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
//sampleEnd
}