当前位置:   article > 正文

Kotlin 指南之二:控制流程

Kotlin 指南之二:控制流程

Kotlin 指南之二:控制流程

本文是系列文章,是 Java 转 Kotlin 指南 的细节补充,根据 Kotlin 官方文档 进行了翻译和修改。如果觉得有用,请点赞、收藏哦!

控制流程

if 条件判断

在 Kotlin 中,if 可以是表达式,因此替代了三元操作符 条件 ? 然后 : 否则

var max = a
if (a < b) max = b

// 使用 else
if (a > b) {
    max = a
} else {
    max = b
}

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

// 在表达式中使用 else if
val maxLimit = 1
val maxOrLimit = if (maxLimit > a) maxLimit else if (a > b) a else b
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

if 表达式也可以是代码块,最后的表达式就是返回值。

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

注:在赋值表达式中 else 是必须的。

多分支判断

类似于 Java 的 switch, Kotlin 提供了更灵活的 when

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

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

when 也可以作为表达式使用,配合枚举类也非常简便

enum class Bit {
    ZERO, ONE
}

val numericValue = when (getRandomBit()) {
    Bit.ZERO -> 0
    Bit.ONE -> 1
    // 'else' 这里 else 不是必须的,如果前面没有全部覆盖就必须提供
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

合并部分条件

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

可以使用任意表达式作为条件判断

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

使用 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")
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

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

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

在条件块中绑定条件变量

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

For 循环

For 循环类似于 foreach。

for (item in collection) print(item)

for (item: Int in ints) {
    // ...
}
  • 1
  • 2
  • 3
  • 4
  • 5

支持区间表达式

for (i in 1..3) {
    println(i)
}

for (i in 6 downTo 0 step 2) {
    println(i)
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

如果需要使用索引值,可以如下获取

for (i in array.indices) {
    println(array[i])
}

for ((index, value) in array.withIndex()) {
    println("the element at $index is $value")
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

while 循环

while 和 do while 执行循环直到不满足条件,while 先检查再执行,do while 先执行一次再检查。

while (x > 0) {
    x--
}

do {
    val y = retrieveData()
} while (y != null)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

跳转

Kotlin 也支持 break 和 continue 来跳出循环。同时还支持使用 @ 来跳到指定的标签。

loop@ for (i in 1..100) {
    for (j in 1..100) {
        if (...) break@loop
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5

异常

Kotlin 的异常与 Java 类似,使用 throw 抛出异常,使用 try catch finally 来处理。

try {
    // some code
} catch (e: SomeException) {
    // handler
} finally {
    // optional finally block
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

同时,try 可以是表达式。

val a: Int? = try { input.toInt() } catch (e: NumberFormatException) { null }
  • 1

如果觉得有用请点赞、收藏吧!

下一篇:Kotlin 指南之三:包和导入

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/992393
推荐阅读
相关标签
  

闽ICP备14008679号