分支条件:
1 when (x) {
2 parseInt(s) -> print("s encodes x")
3 else -> print("s does not encode x")
4 }
还可以用in或!in检查一个范围(5.2)或集合:
1 when (x) {
2 in 1..10 -> print("x is in the range")
3 in validNumbers -> print("x is valid")
4 !in 10..20 -> print("x is outside the range")
5 else -> print("none of the above")
6 }
另一种情况,可以用is或!is检查特别类型。注意,由于智能转换(5.4),不需要任何额外的检查就可以访问类型的方法和属性:
1 val hasPrefix = when(x) {
2 is String -> x.startsWith("prefix")
3 else -> false
4 }
when还可以用来替换if-else链。如果没有变量,分支条件就是简单的布尔表达式,且在when条件为true时,执行该分支:
1 when {
2 x.isOdd() -> print("x is odd")
3 x.isEven() -> print("x is even")
4 else -> print("x is funny")
5 }
查看:when语法(6.2.3.4.2.1)。
2.3.3. for循环
for循环遍历提供的任何一个迭代器。句法如下:
1 for (item in collection)
2 print(item)
循环体可以是一个代码块。
1 for (item: Int in ints) {
2 // ...
3 }
如前所述,for循环遍历提供的任何一个迭代器,即:
—— 有成员iterator()或扩展函数iterator(),它返回类型:
—— 有成员next()或扩展函数next(),和
—— 有返回布尔类型的成员hasNext()或扩展函数hasNext()。
所有这三个函数是需要作为操作符的。
如果要利用索引遍历一个数组或列表,可以这样做:
1 for (i in array.indices)
2 print(array[i])
注意,这句“遍历一个范围”是由编译器优化实现的,不需要产生额外的对象。
或者,可以用withIndex库函数:
1 for ((index, value) in array.withIndex()) {
2 println("the element at $index is $value")
3 }
查看:for语法(6.2.3.3)。
2.3.4. while循环
while和do…while都是如常规一样工作:
1 while (x > 0) {
2 x--
3 }
4
5 do {
6 val y = retrieveData()
7 } while (y != null) // y is visible here!
查看:while语法(6.2.3.3)。
2.3.5. 循环的中断和继续
Kotlin开发语言支持循环中的传统break和continue操作符。查看:返回和跳转(2.4)。
2.4. 返回和跳转
Kotlin开发语言有三种结构化的跳转操作符:
—— return。默认情况下,由最近的函数返回,或匿名函数的返回。
—— break。终止最近一层循环。
—— continue。继续最近一层循环的下一步。
2.4.1. 中断和继续标签
在Kotlin开发语言中,任何表达式都可以带标签。标签的格式是在标识符后跟@来表示,如:abc@,fooBar@都是合法的标签(查看:语法(6.2))。为了标记表达式,只需要在其前面加上标签即可:
1 loop@ for (i in 1..100) {
2 // ...
3 }
现在,就可以break或continue到标签了:
1 loop@ for (i in 1..100) {
2 for (j in 1..100) {
3 if (...)
4 break@loop
5 }
6 }
带有标签的break跳转到标记loop之后的执行点。Continue继续进行标记loop的下一步。
2.4.2. 在标签处返回
Kotlin开发语言在函数体、局部函数和对象表达式中,允许函数嵌套。Return允许我们有外部函数返回。最重要的用例是由Lambda表达式返回。我们这样编写回调:
1 fun foo() {
2 ints.forEach {
3 if (it == 0) return
4 print(it)
5 }
6 }
返回表达式是由最近函数返回,即:foo。(注意:这样对Lambda表达式仅支持非局部返回到内嵌函数(4.1.5)。)如果要从Lambda表达式返回,就需要标记它限制返回:
1 fun foo() {
2 ints.forEach lit@ {
3 if (it == 0) return@lit
4 print(it)
5 }
6 }
现在,就仅从Lambda表达式返回。通常,最方便的是用隐含标签:这样标签与传递给Lambda表达式的函数同名。
1 fun foo() {
2 ints.forEach {
3 if (it == 0) return@forEach
4 print(it)
5 }
6 }
或者,可以用匿名函数(4.2.3.3)替代Lambda表达式。在匿名函数中的return语句是从匿名函数自身返回。
1 fun foo() {
2 ints.forEach(fun(value: Int) {
3 if (value == 0) return
4 print(value)
5 })
6 }
当返回一个值是,解析器优先给出恰当的返回,如:
就是“在标签@a处返回1”而不是“返回标签表达式(@a 1)”。