📜  Kotlin when(1)

📅  最后修改于: 2023-12-03 15:02:32.331000             🧑  作者: Mango

Kotlin when

when is a powerful control flow construct in the Kotlin programming language. It is similar to the switch statement in other languages but offers more flexibility and expressiveness. In this article, we will explore the various features of when and how it can be used effectively in your Kotlin code.

Syntax

The basic syntax of when in Kotlin is as follows:

when (variable) {
    value1 -> action1
    value2 -> action2
    value3, value4 -> action3
    else -> defaultAction
}

Here, variable is the expression that will be evaluated, and the actions associated with the matching values will be executed. The values can be constants, variables, or even expressions.

You can also use ranges and other conditions in when expressions:

when (variable) {
    in 1..10 -> action1
    is String -> action2
    !is Number -> action3
    else -> defaultAction
}
Usage
Matching Single Values

The simplest use of when is to match a single value against a set of possibilities. Each branch is evaluated in sequential order until a match is found. For example:

fun processNumber(number: Int) {
    when (number) {
        0 -> println("Zero")
        1 -> println("One")
        2 -> println("Two")
        else -> println("Other")
    }
}
Matching Multiple Values

You can match multiple values by separating them with commas. In such cases, the same action will be executed for all matching values. For example:

fun processNumber(number: Int) {
    when (number) {
        1, 2 -> println("Small")
        in 3..10 -> println("Medium")
        else -> println("Large")
    }
}
Using Conditions and Ranges

when can also utilize conditions and ranges to perform more complex pattern matching. Here are a few examples:

fun processNumber(number: Int) {
    when {
        number < 0 -> println("Negative")
        number in 0..10 -> println("Small")
        number > 10 && number <= 100 -> println("Medium")
        else -> println("Large")
    }
}

fun processInput(input: Any) {
    when (input) {
        is String -> println("String: ${input.length}")
        is Int -> {
            val squared = input * input
            println("Squared: $squared")
        }
        else -> println("Unknown input")
    }
}
Returning Values

In Kotlin, when can also be used as an expression that returns a value. Each branch can have its own result, and the result of the matching branch will be assigned to a variable or returned immediately. For example:

fun interpretResult(result: Int) = when (result) {
    0 -> "Success"
    in 1..10 -> "Partial Success"
    else -> "Failure"
}
Conclusion

The when expression in Kotlin allows for powerful pattern matching and decision-making in a readable and concise manner. It supports multiple values, conditions, ranges, and can even be used as an expression to return a result. Understanding and utilizing when effectively can greatly enhance the readability and maintainability of your Kotlin code.