Kotlin

How to implement switch-case statement in Kotlin

19 September 2026 · 10 min read

How to implement switch-case statement in Kotlin

Kotlin, a modern and concise programming language, offers powerful features for developers. While Kotlin doesn’t have a traditional “switch-case” statement like Java or C++, it provides the when expression, which serves a similar purpose with enhanced flexibility and readability. Understanding how to implement switch-case statement in Kotlin using the when expression is crucial for writing clean and efficient code. This guide will walk you through the intricacies of the when expression, demonstrating its usage with practical examples and best practices. We’ll explore how to handle different data types, multiple conditions, and complex scenarios, ensuring you can effectively control the flow of your Kotlin applications and avoid nested if-else statements for better code maintainability. The when expression is a cornerstone of Kotlin’s expressive syntax, enabling you to create robust and easily understandable code.

Understanding the Kotlin when Expression

The when expression in Kotlin is a powerful control flow statement that allows you to execute different blocks of code based on the value of an expression. It’s often described as Kotlin’s version of a switch statement, but it goes beyond the capabilities of traditional switch-case constructs. Unlike switch statements in other languages, the when expression can evaluate various types of conditions, including equality checks, range checks, type checks, and even custom boolean expressions. This makes it incredibly versatile for handling different scenarios in your code. According to Kotlin’s official documentation, the when expression is designed to be more concise and readable than a series of nested if-else statements, leading to cleaner and more maintainable code. Think of it as a smart, enhanced way to direct your program’s flow based on different conditions.

One of the key advantages of the when expression is its ability to return a value. This means you can use it directly in assignments or as part of a larger expression. For instance, you can assign the result of a when expression to a variable, making your code more expressive and reducing the need for temporary variables. Furthermore, the when expression requires exhaustiveness when used with sealed classes or enums. This means you must handle all possible cases, ensuring that your code is robust and prevents unexpected behavior. If you don’t cover all cases, the compiler will issue an error, forcing you to address the missing branches. This feature significantly improves code safety and reliability. The Kotlin team emphasizes that this behavior is a key aspect of writing sound, reliable code. Kotlin Documentation on When Expression provides more details on these advanced features. Consider also Baeldung’s Kotlin When Article for extra information and examples.

The flexibility of the when expression extends to handling multiple conditions in a single branch. You can use commas to specify multiple values that should trigger the same block of code. This can significantly reduce code duplication and improve readability, especially when dealing with several similar cases. Additionally, you can use the in operator to check if a value falls within a specific range or belongs to a collection. This is particularly useful for handling numerical ranges or checking membership in a set of predefined values. The when expression also supports the is operator, which allows you to perform type checking and execute different code based on the type of a variable. This is extremely handy when working with polymorphic types or dealing with data from external sources where the type might not be known at compile time.

Implementing Basic Switch-Case Logic with when

At its core, the when expression allows you to emulate the functionality of a traditional switch-case statement. The basic syntax involves providing an expression to evaluate, followed by a series of branches that specify the conditions and corresponding code to execute. Each branch consists of a condition and an arrow (->), followed by the code block to be executed if the condition is met. The else branch acts as the default case, similar to the default keyword in a switch statement. If none of the preceding conditions are met, the code in the else branch will be executed. This ensures that there is always a fallback option, preventing unexpected behavior when the input doesn’t match any of the specified cases. The code within each branch can be a single expression or a block of code enclosed in curly braces.

For instance, consider a scenario where you want to determine the day of the week based on a numerical input. You can use a when expression to map each number (1 to 7) to the corresponding day name. Here’s how you can implement switch-case statement in Kotlin for this scenario:

fun getDayOfWeek(dayNumber: Int): String { return when (dayNumber) { 1 -> "Monday" 2 -> "Tuesday" 3 -> "Wednesday" 4 -> "Thursday" 5 -> "Friday" 6 -> "Saturday" 7 -> "Sunday" else -> "Invalid day number" } } 

In this example, the when expression evaluates the value of dayNumber and returns the corresponding day name. If dayNumber is not within the range of 1 to 7, the else branch is executed, returning “Invalid day number”. This demonstrates how the when expression can be used to handle multiple cases and provide a default fallback option. This construct offers improved readability compared to nested if-else statements.

Featured Snippet: The when expression in Kotlin acts as a switch-case replacement, evaluating an expression and executing a corresponding code block. Each branch consists of a condition followed by an arrow (->) and the code to execute. The else branch serves as the default case when no other conditions are met. This allows for cleaner and more readable code compared to nested if-else statements, especially when dealing with multiple conditions or complex logic.

Advanced Usage of the when Expression

The when expression in Kotlin offers several advanced features that go beyond the basic switch-case functionality. One of these features is the ability to use multiple conditions in a single branch. This can be achieved by separating the conditions with commas. For example, you might want to execute the same code for both Saturday and Sunday. Instead of duplicating the code block, you can combine the conditions into a single branch:

fun isWeekend(day: String): Boolean { return when (day) { "Saturday", "Sunday" -> true else -> false } } 

Another advanced feature is the use of ranges. You can use the in operator to check if a value falls within a specific range. This is particularly useful for handling numerical ranges or checking if a character is within a certain set. For instance, you can determine if a number is within the range of 1 to 10 using the following code:

fun isWithinRange(number: Int): Boolean { return when (number) { in 1..10 -> true else -> false } } 

Furthermore, the when expression can be used with the is operator to perform type checking. This allows you to execute different code based on the type of a variable. This is useful when working with polymorphic types or dealing with data from external sources where the type might not be known at compile time. For example:

fun describe(obj: Any): String { return when (obj) { is String -> "It's a String with length ${obj.length}" is Int -> "It's an Int with value ${obj}" else -> "Unknown type" } } 

Best Practices for Using when in Kotlin

To effectively use the when expression in Kotlin, it’s important to follow some best practices. First, always consider using the else branch to handle unexpected or default cases. This prevents your code from crashing or producing unexpected results when the input doesn’t match any of the specified conditions. It also helps make your code more robust and reliable. Leaving out the else branch when it should be present can lead to runtime errors and difficult-to-debug issues, especially when dealing with enums or sealed classes.

Second, strive for readability and conciseness. Use meaningful variable names and keep the code blocks within each branch short and focused. If a branch requires a large amount of code, consider extracting it into a separate function to improve code organization and maintainability. Avoid nesting when expressions excessively, as this can make your code difficult to understand and debug. Instead, try to simplify the logic or use helper functions to break down complex scenarios into smaller, more manageable parts. Always aim for code that is easy to read, understand, and maintain. According to research by Steve McConnell in “Code Complete,” code is read far more often than it is written, so optimizing for readability is crucial.

Third, ensure that your when expressions are exhaustive when working with sealed classes or enums. Kotlin’s compiler will enforce this requirement, preventing you from missing any possible cases. This helps ensure that your code is complete and handles all possible scenarios. Take advantage of Kotlin’s features, such as multiple conditions, ranges, and type checking, to simplify your code and make it more expressive. This can lead to more concise and readable code that is easier to understand and maintain. The when expression is a powerful tool, but it’s important to use it wisely and follow best practices to ensure that your code is clean, efficient, and reliable. Understanding how to implement switch-case statement in Kotlin correctly and effectively boils down to these principles.

  • Always include an else branch for default cases.
  • Keep code blocks within each branch short and focused.
  1. Define the expression to be evaluated in the when statement.
  2. Specify the conditions for each branch using ->.
  3. Include an else branch for default behavior.
Infographic showing When vs If-Else performance and readability
FAQ about Kotlin `when` Expression ----------------------------------
What is the Kotlin `when` expression?
The `when` expression is Kotlin's equivalent of a switch statement, providing a concise and flexible way to execute different code blocks based on the value of an expression.
How is the `when` expression different from a switch statement in Java?
The `when` expression is more flexible than Java's switch statement. It supports various types of conditions, including equality checks, range checks, type checks, and custom boolean expressions. It can also return a value directly.
Is the `else` branch required in a `when` expression?
The `else` branch is required when the compiler cannot guarantee that all possible cases are covered, such as when using a regular class or variable. However, it's not required when using sealed classes or enums, as the compiler can verify that all cases are handled.
Can I use multiple conditions in a single branch of a `when` expression?
Yes, you can use commas to separate multiple conditions in a single branch, allowing you to execute the same code block for multiple values.
Mastering the `when` expression opens doors to writing more elegant and efficient Kotlin code. It's more than just a replacement for switch-case; it's a powerful tool for expressing complex logic in a clear and concise manner. By understanding its features and following best practices, you can significantly improve the readability and maintainability of your Kotlin projects. [Start incorporating the `when` expression](https://courthousezoological.com/n7sqp6kh?key=e6dd02bc5dbf461b97a9da08df84d31c) into your workflow today and experience the benefits firsthand. Consider exploring other Kotlin features like coroutines and data classes to further enhance your coding skills. For a deep dive, consult [Tutorialspoint's Kotlin When Expression Guide](https://www.tutorialspoint.com/kotlin/kotlin_when_expression.htm) for more information.

Question & Answer :
How to implement equivalent of following Java switch statement code in Kotlin?

switch (5) { case 1: // Do code break; case 2: // Do code break; case 3: // Do code break; } 

You could do it like this:

when (x) { 1 -> print("x == 1") 2 -> print("x == 2") else -> { // Note the block print("x is neither 1 nor 2") } } 

Extracted from official help.