📅  最后修改于: 2023-12-03 14:43:41.114000             🧑  作者: Mango
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.
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.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
Here are some of the benefits of using Kotlin switch:
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.