We have all learned Switch cases in other programming languages like Java and C++. A switch case integrates control flow in a programming language. However, in Kotlin, there is no Switch case. Instead, we use When. When is a flexible and easy alternative to Switch in Kotlin. The reason Kotlin replaced Switch with When is that, unlike Switch, When can be used both as a statement and as an expression. It also supports a wide range of conditions including ranges and types.
Switch Case in Kotlin: Using ‘When’ as a Replacement with Examples
The basic syntax of the ‘when’ expression in Kotlin:
1 2 3 4 5 6 7 8 9 |
when (variable) { value1 -> { // Code block } value2 -> { // Code block } else -> { // Default code block } } |
1. Code Example of using When in Kotlin:
In this example, we are integrating When as a replacement for Switch in Kotlin. We are creating a system where users can pass the day name and it will tell us whether it is a weekend or a weekday.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
fun getDayType(day: String): String { return when (day) { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> "Weekday" "Saturday", "Sunday" -> "Weekend" else -> "Invalid day" } } fun main() { println(getDayType("Tuesday")) println(getDayType("Sunday")) } // Output Weekday Weekend |
2. Using Range with When in Kotlin:
In this example, we will be using different number ranges and if the given score is between these ranges it prints a message.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
fun evaluateScore(score: Int): String { return when (score) { in 90..100 -> "Excellent" in 75..89 -> "Good" in 50..74 -> "Average" in 0..49 -> "Needs Improvement" else -> "Invalid Score" } } fun main() { println(evaluateScore(85)) println(evaluateScore(45)) } // Output Good Needs Improvement |
Thanks for reading our article, Happy Coding.