条件与循环

If 表达式

在 Kotlin 中,if 是一个表达式:它会返回一个值。 因此就不需要三元运算符(条件 ? 然后 : 否则),因为普通的 if 就能胜任这个角色。

1. fun main() {
2. val a = 2
3. val b = 3

5. //sampleStart
6. var max = a
7. if (a < b) max = b

9. // With else
10. if (a > b) {
11. max = a
12. } else {
13. max = b
14. }

16. // 作为表达式
17. max = if (a > b) a else b

19. // You can also use `else if` in expressions:
20. val maxLimit = 1
21. val maxOrLimit = if (maxLimit > a) maxLimit else if (a > b) a else b

23. //sampleEnd
24. println("max is $max")
25. println("maxOrLimit is $maxOrLimit")
26. }

if 表达式的分支可以是代码块,这种情况最后的表达式作为该块的值:

1. val max = if (a > b) {
2. print("Choose a")
3. a
4. } else {
5. print("Choose b")
6. b
7. }

If you’re using if as an expression, for example, for returning its value or assigning it to a variable, the else branch is mandatory.

When 表达式

when defines a conditional expression with multiple branches. It is similar to the switch statement in C-like languages. Its simple form looks like this.

1. when (x) {
2. 1 -> print("x == 1")
3. 2 -> print("x == 2")
4. else -> {
5. print("x is neither 1 nor 2")
6. }
7. }

when 将它的参数与所有的分支条件顺序比较,直到某个分支满足条件。

when 既可以作为表达式使用也可以作为语句使用。如果它被当做表达式, 第一个符合条件的分支的值就是整个表达式的值,如果当做语句使用, 则忽略个别分支的值。 类似于 if,每一个分支可以是一个代码块,它的值是块中最后的表达式的值。

如果其他分支都不满足条件将会求值 else 分支。 如果 when 作为一个表达式使用,那么必须有 else 分支, 除非编译器能够检测出所有的可能情况都已经覆盖了, 例如,对于 枚举(enum)类条目与密封(sealed)类子类型〕。

1. enum class Bit {
2. ZERO, ONE
3. }

5. val numericValue = when (getRandomBit()) {
6. Bit.ZERO -> 0
7. Bit.ONE -> 1
8. // 'else' is not required because all cases are covered
9. }

In when statements, the else branch is mandatory in the following conditions:

  • when has a subject of a Boolean, enum, or sealed type, or their nullable counterparts.
  • branches of when don’t cover all possible cases for this subject.
1. enum class Color {
2. RED, GREEN, BLUE
3. }

5. when (getColor()) {
6. Color.RED -> println("red")
7. Color.GREEN -> println("green")
8. Color.BLUE -> println("blue")
9. // 'else' is not required because all cases are covered
10. }

12. when (getColor()) {
13. Color.RED -> println("red") // no branches for GREEN and BLUE
14. else -> println("not red") // 'else' is required
15. }

To define a common behavior for multiple cases, combine their conditions in a single line with a comma:

1. when (x) {
2. 0, 1 -> print("x == 0 or x == 1")
3. else -> print("otherwise")
4. }

可以用任意表达式(而不只是常量)作为分支条件

1. when (x) {
2. s.toInt() -> print("s encodes x")
3. else -> print("s does not encode x")
4. }

还可以检测一个值在(in)或者不在(!in)一个区间或者集合中:

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)一个特定类型的值。注意: 由于智能转换,你可以访问该类型的方法与属性而无需任何额外的检测。

1. fun hasPrefix(x: Any) = when(x) {
2. is String -> x.startsWith("prefix")
3. else -> false
4. }

when 也可以用来取代 if-else if 链。 如果不提供参数,所有的分支条件都是简单的布尔表达式,而当一个分支的条件为真时则执行该分支:

1. when {
2. x.isOdd() -> print("x is odd")
3. y.isEven() -> print("y is even")
4. else -> print("x+y is odd")
5. }

可以使用以下语法将 when 的主语(subject,译注:指 when 所判断的表达式)捕获到变量中:

1. fun Request.getBody() =
2. when (val response = executeRequest()) {
3. is Success -> response.body
4. is HttpError -> throw HttpException(response.status)
5. }

在 when 主语中引入的变量的作用域仅限于 when 主体。

For 循环

for 循环可以对任何提供迭代器(iterator)的对象进行遍历,这相当于像 C# 这样的语言中的 foreach 循环。 for 的语法如下所示:

1. for (item in collection) print(item)

for 循环体可以是一个代码块。

1. for (item: Int in ints) {
2. // ……
3. }

如上所述,for 可以循环遍历任何提供了迭代器的对象。这意味着:

  • 有一个成员函数或者扩展函数 iterator() 返回 Iterator<>:
  • 有一个成员函数或者扩展函数 next()
  • 有一个成员函数或者扩展函数 hasNext() 返回 Boolean。

这三个函数都需要标记为 operator。

如需在数字区间上迭代,请使用区间表达式:

1. fun main() {
2. //sampleStart
3. for (i in 1..3) {
4. println(i)
5. }
6. for (i in 6 downTo 0 step 2) {
7. println(i)
8. }
9. //sampleEnd
10. }

对区间或者数组的 for 循环会被编译为并不创建迭代器的基于索引的循环。

如果你想要通过索引遍历一个数组或者一个 list,你可以这么做:

1. fun main() {
2. val array = arrayOf("a", "b", "c")
3. //sampleStart
4. for (i in array.indices) {
5. println(array[i])
6. }
7. //sampleEnd
8. }

或者你可以用库函数 withIndex:

1. fun main() {
2. val array = arrayOf("a", "b", "c")
3. //sampleStart
4. for ((index, value) in array.withIndex()) {
5. println("the element at $index is $value")
6. }
7. //sampleEnd
8. }

while 循环

while and do-while loops execute their body continuously while their condition is satisfied. The difference between them is the condition checking time:

  • while checks the condition and, if it’s satisfied, executes the body and then returns to the condition check.
  • do-while executes the body and then checks the condition. If it’s satisfied, the loop repeats. So, the body of do-while executes at least once regardless of the condition.
1. while (x > 0) {
2. x--
3. }

5. do {
6. val y = retrieveData()
7. } while (y != null) // y 在此处可见

循环中的 break 与 continue

在循环中 Kotlin 支持传统的 break 与 continue 操作符。参见返回与跳转。