# Kotlin 循控制
循环控制语句也是每门语言不可缺少的一部分,一般就是我们所熟知的 for 、 while 、 do-while 。Kotlin 循环其实几乎和 Java 中 的一模一样。

# for 循环
*for 循环 * 可以对任何提供迭代器(iterator)的对象进行遍历,for 循环仅以唯一一种形式存在,和 Java 的 for-each 循环一致。其写法 for <item> in <elements> 和 C# 一样。和 Java 类似,循环最常见的应用就是迭代集合,具体语法如下:
| for (item in list) println(item) | |
| // 循环体还可以是个代码块 | |
| for (item in list) { | |
|     //... | |
| } | |
| val items = listOf("java", "kotlin", "android") | |
| //for-in 遍历 | |
| for (item in items) {//for 遍历集合 | |
| println("lang $item") | |
| } | |
| // 遍历索引 | |
| for (index in items.indices) {// 类似于 java 中的数组的 length-index 的遍历 | |
| println("The $index index is ${items[index]}") | |
| } | 
# while 和 do-while 循环
Kotlin 中 while 和 do-while 循环,它们的语法和 Java 中相应的循环没什么区别:
| // 当 condition 为 true 时执行循环体 | |
| while(condition) { | |
|     /*...*/ | |
| } | |
| // 循环体第一次会无条件地执行。此后,当 condition 为 true 时才执行 | |
| do { | |
|     /*...*/ | |
| } while (condition) | |
| val items = listOf("java", "kotlin", "android") | |
| var index = 0 | |
| while (index < items.size) {//while 循环的遍历方式 | |
| println("The $index lang is ${items[index++]}") | |
| } | 
# 迭代区间和数列
如上所述,for 可以循环遍历任何提供了迭代器的对象。即:有一个成员函数或者扩展函数 iterator() ,它的返回类型,有一个成员函数或者扩展函数 next() ,并且有一个成员函数或者扩展函数 hasNext() 返回 Boolean 。
如需在数字区间上迭代,请使用区间表达式:
| for (i in 1..10) {// 遍历区间,注意 Kotlin 的区间的包含或是闭合的。 | |
| print("$i ") | |
| } | |
| // 输出结果: 1 2 3 4 5 6 7 8 9 10  | |
| for (i in 1 until 10) { | |
| print("$i ") | |
| } | |
| // 输出结果: 1 2 3 4 5 6 7 8 9 | |
| for (i in 10 downTo 1 step 2) { | |
| print("$i ") | |
| } | |
| // 输出结果: 10 8 6 4 2 | 
对区间或者数组的 for 循环会被编译为并不创建迭代器的基于索引的循环。
如果想要通过索引遍历一个数组或者一个 list,可以这么做:
| for (i in array.indices) {// 遍历索引 | |
| println(array[i]) | |
| } | 
或者可以用库函数 withIndex :
| for ((index, value) in array.withIndex()) { | |
| println("the element at $index is $value") | |
| } | 
# 循环中的 break 与 continue
在循环中 Kotlin 支类似 Java 中 break 和 continue 操作符。
- break:终止最直接包围它的循环;
- continue:继续下一次最直接包围它的循环。
| for (i in 1..100) { | |
| if (i % 2 == 0) continue // 如果 i 能整除于 2,跳出本次循环,否则进入下层循环 | |
| for (j in 1..100) { | |
| if (j < 50) break // 如果 j 小于 50 ,终止循环。 | |
|     } | |
| } | 
