Kotlin条件控制表达式

119 阅读1分钟

常见的条件表达式:if, when, for, while

这些表达式在日常的编程工作中几乎是每天要写的,这里举一些例子:

val max = if (a > b) a else b
when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { // Note the block
        print("x is neither 1 nor 2")
    }
}
when (x) {
    parseInt(s) -> print("s encodes x")
    else -> print("s does not encode x")
}
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")
}
for (i in 1..3) {
    println(i)
}
for (i in 6 downTo 0 step 2) {
    println(i)
}
while (x > 0) {
    x--
}

do {
    val y = retrieveData()
} while (y != null) // y is visible here!