Kotlin conditional control


Release date:2023-09-22 Update date:2023-10-13 Editor:admin View counts:293

Label:

Kotlin conditional control

IF expression

One if statement contains a Boolean expression and one or more statements.

// Traditional use
var max = a
if (a < b) max = b

// use else
var max: Int
if (a > b) {
    max = a
} else {
    max = b
}

// As an expression
val max = if (a > b) a else b

We can also put IF result of the expression is assigned to a variable.

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

This also means that I don’t need to have a ternary operator like Java, because we can use it to simply implement:

val c = if (condition) a else b

Example

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("The value of c is $c")
}

The output is as follows:

X equals 0
The value of c is 2

Use interval

Use in operator to detect whether a number is within a specified interval in the format of x..y :

Example

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

The output is as follows:

X is within the interval

When expression

when compare its parameters sequentially with all branch conditions until a branch meets the condition.

when can be used either as an expression or as a statement. If it is treated as an expression, the value of the qualified branch is the value of the entire expression, and if used as a statement, the value of individual branches is ignored.

when similar to other languages switch operator. Its simplest formis as follows:

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { // Pay attention to this block
        print("X is not 1, nor is it 2")
    }
}

In when , else with switch of default . If the other branches do not meet the conditions, they will be evaluated. else branch.

If many branches need to be handled in the same way, you can put multiple branch conditions together and separate them with commas:

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

We can also detect a value in ( in ) or not present ( !in ) in an interval or set:

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 detect that a value is is ) or not ( !is a value of a specific type Note: due to smart conversions, you can access this type of methods and properties without any additional detection.

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

when can also be used to replace if-else if chain. If no parameters are provided, all branch conditions are simple Boolean expressions, and when the condition of a branch is true, the branch 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 -> { // Pay attention to this block
            println("X is not 1, nor is it 2")
        }
    }

    when (x) {
        in 0..10 -> println("X is within the range of this interval")
        else -> println("X is not within the range of this interval")
    }
}

Output result:

X==0 or x==1
X is not 1, nor is it 2
X is within the range of this interval

when for use in in operator to determine whether an instance is included in the collection:

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 result:

apple is fine too

Powered by TorCMS (https://github.com/bukun/TorCMS).