📜  kotlin swithc - Kotlin (1)

📅  最后修改于: 2023-12-03 14:43:41.114000             🧑  作者: Mango

Kotlin Switch

Kotlin Switch is a powerful feature that helps programmers to write clean and efficient code. With Kotlin switch, you can easily handle multiple cases and take specific actions based on the value of a given variable.

Syntax

The syntax for using Kotlin switch is as follows:

when (variable) {
    value1 -> action1
    value2 -> action2
    value3 -> action3
    else -> defaultAction
}
  • variable: The variable for which you want to switch on.
  • value1, value2, value3, etc.: Possible values for the variable.
  • action1, action2, action3, etc.: Actions to take for each value.
  • else: Optional block of code that is executed if none of the other cases match.
Example

Here is an example of using Kotlin switch to print out whether a given number is positive, negative or zero:

fun main() {
    val number = -5

    when {
        number > 0 -> println("$number is positive")
        number < 0 -> println("$number is negative")
        else -> println("$number is zero")
    }
}

Output:

-5 is negative
Benefits

Here are some of the benefits of using Kotlin switch:

  • Cleaner code: Kotlin switch allows you to write cleaner code by reducing the number of if-else statements required for handling multiple cases.
  • Efficient: Kotlin switch is more efficient than if-else statements, especially when you have a large number of cases to handle.
  • Readable: Switch statements are more readable than chained if-else statements.
Conclusion

Kotlin switch is a powerful feature that can help you write cleaner and more efficient code. By using Kotlin switch, you can handle multiple cases with ease and make your code more readable.