YouTip LogoYouTip

Kotlin Condition Control

IF Expressions

An if statement consists of a boolean expression followed by one or more statements.

// Traditional usage
var max = a
if (a  b) {
    max = a
} else {
    max = b
}

// As an expression
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 I don't need a ternary operator like in Java, because we can simply implement it using this:

val c = if (condition) a else b

Example

fun main(args: Array<String>) {
    var x = 0
    if(x>0){
        println("x is greater than 0")
    }else if(x==0){
        println("x is equal to 0")
    }else{
        println("x is less than 0")
    }

    var a = 1
    var b = 2
    val c = if (a>=b) a else b
    println("The value of c is $c")
}

The output is:

x is equal to 0
The value of c is 2

Using Ranges

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

Example

fun main(args: Array<String>) {
    val x = 5
    val y = 9
    if (x in 1..8) {
        println("x is in the range")
    }
}

The output is:

x is in the range

When Expressions

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

when can be used both as an expression and as a statement. If used as an expression, the value of the satisfied branch becomes the value of the entire expression. If 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 -> { // Note the block
        print("x is neither 1 nor 2")
    }
}

In when, else is like default in switch. If no other branch condition is met, the else branch is evaluated.

If multiple branches need to be handled in the same way, the branch conditions can be combined, separated by commas:

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

We can also check if a value is in (in) or not in (!in) a range or 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 if a value is (is) or is not (!is) of a specific type. Note: Due to smart casting, you can access the methods and properties of the 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 the branch whose condition is true is executed:

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

Example

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 -> { // Note the block
            println("x is neither 1 nor 2")
        }
    }

    when (x) {
        in 0..10 -> println("x is in the range")
        else -> println("x is outside the range")
    }
}

Output:

x == 0 or x == 1
x is neither 1 nor 2
x is in the range

Using the in operator in when to check if 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
← Kotlin Class ObjectKotlin Basic Syntax β†’