Question
How can I write the Kotlin equivalent of this Java switch statement?
switch (5) {
case 1:
// Do code
break;
case 2:
// Do code
break;
case 3:
// Do code
break;
}
I want to understand how switch-case style branching is implemented in Kotlin.
Short Answer
By the end of this page, you will understand that Kotlin does not use switch. Instead, it uses the more flexible when construct. You will learn the basic syntax, how to match values, how multiple branches work, how when can return a value, and how it is commonly used in real Kotlin code.
Concept
Kotlin does not have a switch statement like Java. The Kotlin equivalent is when.
when is used for conditional branching: it lets your program choose one block of code from several possible options.
In Java, switch is mainly designed for matching a value against cases. In Kotlin, when is more powerful:
- It can match exact values.
- It can combine multiple matching values in one branch.
- It can be used as a statement.
- It can also be used as an expression that returns a value.
- It can check ranges, types, and arbitrary conditions.
This matters because branching is one of the most common tasks in programming. You use it when:
- handling menu choices
- mapping status codes
- validating input
- deciding UI behavior
- processing API results
So while the question starts with "How do I write switch in Kotlin?", the bigger idea is learning how Kotlin handles multi-branch decisions using when.
Mental Model
Think of when like a receptionist checking a visitor's badge.
- If the badge says
1, send them to Room A. - If it says
2, send them to Room B. - If it says
3, send them to Room C. - If it does not match anything, send them to the help desk.
Java switch is like an older desk with a fixed set of slots.
Kotlin when is like a smarter desk that can handle:
- exact badge numbers
- groups of badge numbers
- badge ranges
- even badge types
So when is not just a replacement for switch; it is a more capable way to make decisions.
Syntax and Examples
Basic syntax
The Java code in the question becomes this in Kotlin:
when (5) {
1 -> {
// Do code
}
2 -> {
// Do code
}
3 -> {
// Do code
}
}
Key syntax differences from Java
- No
switchkeyword; usewhen. - No
casekeyword. - No
breakneeded. - Use
->to separate a match from its code. - Braces around each branch are optional if there is only one statement.
Simple example
val number = 2
when (number) {
1 -> println("One")
2 -> println("Two")
3 -> println("Three")
}
This prints:
Two
Using
Step by Step Execution
Consider this example:
val number = 2
when (number) {
1 -> println("One")
2 -> println("Two")
3 -> println("Three")
else -> println("Other")
}
Step by step
numberis assigned the value2.- The
whenblock checksnumber. - Kotlin compares
numberwith the first branch value:1. 2 == 1is false, so it moves to the next branch.- Kotlin compares
numberwith the second branch value:2. 2 == 2is true, so it runs:
println("Two")
- The output is:
Real World Use Cases
when is used all over real Kotlin programs.
1. Handling menu choices
val choice = 2
when (choice) {
1 -> println("Start game")
2 -> println("Load game")
3 -> println("Exit")
else -> println("Invalid option")
}
2. Mapping status codes to messages
val statusCode = 404
val message = when (statusCode) {
200 -> "OK"
401 -> "Unauthorized"
404 -> "Not Found"
500 -> "Server Error"
else -> "Unknown Status"
}
3. UI state handling
val screenState = "loading"
when (screenState) {
"loading" -> println("Show spinner")
"success" -> println()
-> println()
-> println()
}
Real Codebase Usage
In production Kotlin code, developers often use when in ways that go beyond simple value matching.
1. Returning values cleanly
Instead of setting a variable and changing it later, developers often write:
val resultText = when (resultCode) {
0 -> "Pending"
1 -> "Success"
2 -> "Failed"
else -> "Unknown"
}
This avoids mutable state and keeps logic compact.
2. Guarding unsupported cases
fun getRoleName(roleId: Int): String {
return when (roleId) {
1 -> "Admin"
2 -> "Editor"
3 -> "Viewer"
else -> "Invalid role"
}
}
This is a common validation pattern.
3. Handling sealed classes and enums
Kotlin developers often use when with enums and sealed classes because it reads clearly.
Common Mistakes
1. Trying to use switch in Kotlin
Broken code:
switch (5) {
case 1:
println("One")
}
Why it fails:
- Kotlin has no
switchkeyword. - Kotlin uses
wheninstead.
Correct code:
when (5) {
1 -> println("One")
}
2. Writing case and break
Broken code:
when (5) {
case 1:
println("One")
break
}
Why it fails:
caseis Java syntax, not Kotlin.breakis not needed inwhenbranches.
Comparisons
| Concept | Java switch | Kotlin when |
|---|---|---|
| Keyword | switch | when |
| Branch label | case | direct value or condition |
| Default branch | default | else |
Needs break | Usually yes | No |
| Fall-through | Yes, unless stopped | No |
| Can return a value | Limited in older Java style | Yes, naturally |
Cheat Sheet
Quick syntax
when (value) {
1 -> println("One")
2 -> println("Two")
else -> println("Other")
}
Multiple matches
when (value) {
1, 2, 3 -> println("Small")
else -> println("Other")
}
Return a value
val text = when (value) {
1 -> "One"
else -> "Other"
}
Condition-based form
when {
value < 0 -> println("Negative")
value == 0 -> println("Zero")
else -> println("Positive")
}
Rules to remember
- Kotlin uses
when, not .
FAQ
Is there a switch statement in Kotlin?
No. Kotlin uses when instead of switch.
What is the Kotlin equivalent of Java switch-case?
The equivalent is when.
when (value) {
1 -> println("One")
else -> println("Other")
}
Do I need break in Kotlin when?
No. Kotlin when does not fall through, so break is not needed.
What is the Kotlin version of default in switch?
Use else.
Can when return a value in Kotlin?
Yes. That is one of its biggest advantages.
Mini Project
Description
Build a small command-based status message program in Kotlin. The program takes a numeric code and prints a message based on that code. This is a practical way to learn how when replaces Java switch-case and how to provide a safe fallback using else.
Goal
Create a Kotlin program that maps numeric command codes to readable messages using when.
Requirements
- Define an integer variable named
commandCode. - Use a
whenblock to handle at least three command values. - Print a different message for each supported command.
- Include an
elsebranch for unsupported values. - Keep the program runnable as a simple Kotlin console application.
Keep learning
Related questions
Accessing Kotlin Extension Functions from Java
Learn how Kotlin extension functions are compiled and how to call them correctly from Java with clear examples and common pitfalls.
Android AlarmManager Example: Scheduling Tasks with AlarmManager
Learn how to use Android AlarmManager to schedule tasks, set alarms, and handle broadcasts with a simple beginner example.
Android Foreground Service Notification Channels in Kotlin
Learn why startForeground fails on Android 8.1 and how to create a valid notification channel for foreground services in Kotlin.