3.4循环语句 for,while,when
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")
}
遍历集合
//定义一个集合
val items = listOf(1, 2, 3, 4)
//循环遍历集合元素输出
for(i in items){
println(i)
}
遍历区间
//循环遍历区间输出
for(i in 11..13){
println(i)
}
while循环
while 和 do..while 照常使用
while (x > 0) {
x--
}
do {
val y = retrieveData()
} while (y != null) // y 在此处可见
例如依次输出1到4:
var i=1
while ( i < 5 ) {
println(i)
i++
}
使用do..while就是:
var j=1
do{
println(j)
j++
}while(j<5)
注:在循环中 Kotlin 支持传统的 break 和 continue 操作符,详情见3.6返回和跳转
when
when 取代了类 C 语言的 switch 操作符。其最简单的形式如下:
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> { // 注意这个块
print("x is neither 1 nor 2")
}
}
when 将它的参数和所有的分支条件顺序比较,直到某个分支满足条件。
when 既可以被当做表达式使用也可以被当做语句使用。如果它被当做表达式, 符合条件的分纸的值就是整个表达式的值,如果当做语句使用, 则忽略个别分支的值。 (像 if 一样,每一个分支可以是一个代码块,它的值 是块中最后的表达式的值。)
如果其他分支都不满足条件将会求值 else 分支。 如果 when 作为一个表达式使用,则必须有 else 分支, 除非编译器能够检测出所有的可能情况都已经覆盖了。
如果很多分支需要用相同的方式处理,则可以把多个分支条件放在一起,用逗号分隔:
when (x) {
0, 1 -> print("x == 0 or x == 1")
else -> print("otherwise")
}
我们可以用任意表达式(而不只是常量)作为分支条件控制流
when (x) {
parseInt(s) -> print("s encodes x")
else -> print("s does not encode x")
}
我们也可以检测一个值在(in)或者不在(!in)一个区间或者集合中:
when (x) {
in 1..10 -> print("x is in the range")
in validNumbers -> print("x is valid")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}
另一种可能性是检测一个值是(is)或者不是(!is)一个特定类型的值。注意: 由于智能转换,你可以访问该类型的方法和属性而无需任何额外的检测。
fun hasPrefix(x: Any) = when(x) {
is String -> x.startsWith("prefix")
else -> false
}
when 也可以用来取代 if-else
、 if
链。 如果不提供参数,所有的分支条件都是简单的布尔表达式,而当一个分支的条件为真时则执行该分支:
when {
x.isOdd() -> print("x is odd")
x.isEven() -> print("x is even")
else -> print("x is funny")
}
例如:
学习成绩在90到100之间评级为A,75到89之间为B,60到74之间为C,60以下为D,满分100,现判断85分评级为什么:
val score = 85
when(score){
in 90..100 -> println("A")
in 75..89 -> println("B")
in 60..74 -> println("C")
in 0..60 -> println("D")
}
作为表达式有返回值(带返回值的必须有else分支):
var level = when(score){
in 90..100 -> 'A'
in 75..89 -> 'B'
in 60..74 -> 'C'
else -> 'D'
}
println(level)