Kotlin Conditional Control

IF Expression

An if statement contains a boolean expression and one or more statements.

// 传统用法
var max = a 
if (a < b) max = b

// 使用 else 
var max: Int
if (a > b) {
    max = a
} else {
    max = b
}
 
// 作为表达式
val max = if (a > b) a else b

We can also assign the result of an IF expression to a variable.

val max = if (a > b) {
    print("Choose a")
    a
} else {
    print("Choose b")
    b
}

This also shows that we don't need a ternary operator like Java, because we can use it to implement it simply:

val c = if (condition) a else b

Examples

fun main(args: Array<String>) {
    var x = 0
    if(x>0){
        println("x 大于 0")
    }else if(x==0){
        println("x 等于 0")
    }else{
        println("x 小于 0")
    }

    var a = 1
    var b = 2
    val c = if (a>=b) a else b
    println("c 的值为 $c")
}

The output is:

x 等于 0
c 的值为 2

Using Ranges

Use the in operator to check whether a number is within a specified range. The range format is:x..y :

Examples

fun main(args: Array<String>) {
    val x = 5
    val y = 9
    if (x in 1..8) {
        println("x 在区间内")
    }
}

The output is:

x 在区间内

When Expression

when compares its argument with all branch conditions in order until a branch satisfies the condition.

when can be used either as an expression or as a statement. If it is used as an expression, the value of the matching branch is the value of the entire expression. If it is used as a statement, the values of individual branches are ignored.

when is similar to the switch operator in other languages. Its simplest form is as follows:

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { // 注意这个块
        print("x 不是 1 ,也不是 2")
    }
}

In when, else is the same as default in switch. If none of the other branches satisfy the condition, the else branch will be evaluated.

If many branches need to be handled in the same way, you can put multiple branch conditions together, separated by commas:

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

We can also check whether a value is in (in) or not in (!in) a range or a collection:

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")
}

Another possibility is to check whether a value is (is) or is not (!is) a value of a specific type. Note: Due to smart casts, you can access the methods and properties of that type without any additional checks.

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

when can also be used to replace an if-else if chain. If no argument is provided, all branch conditions are simple boolean expressions, and a branch is executed when its condition is true:

when {
    x.isOdd() -> print("x is odd")
    x.isEven() -> print("x is even")
    else -> print("x is funny")
}

Examples

fun main(args: Array<String>) {
    var x = 0
    when (x) {
        0, 1 -> println("x == 0 or x == 1")
        else -> println("otherwise")
    }

    when (x) {
        1 -> println("x == 1")
        2 -> println("x == 2")
        else -> { // 注意这个块
            println("x 不是 1 ,也不是 2")
        }
    }

    when (x) {
        in 0..10 -> println("x 在该区间范围内")
        else -> println("x 不在该区间范围内")
    }
}

Output:

x == 0 or x == 1
x 不是 1 ,也不是 2
x 在该区间范围内

Using in wheninoperator to check whether a collection contains an instance:

fun main(args: Array<String>) {
    val items = setOf("apple", "banana", "kiwi")
    when {
        "orange" in items -> println("juicy")
        "apple" in items -> println("apple is fine too")
    }
}

Output:

apple is fine too
Other Extensions