Question

Kotlin switch-case Equivalent: Using when Expression

kotlinswitch-statement

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.

Take Quiz

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 switch keyword; use when.
  • No case keyword.
  • No break needed.
  • 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 else

If you want a default branch like Java's default, use else.

val number = 5

when (number) {
    1 -> println("One")
    2 -> println("Two")
    3 -> println("Three")
    else -> println("Unknown number")
}

Matching multiple values

val day = 6

when (day) {
    1, 7 -> println("Weekend-style check")
    2, 3, 4, 5, 6 -> println("Weekday-style check")
}

when as an expression

Unlike Java switch statements, Kotlin when can return a value.

val number = 3

val label = when (number) {
    1 -> "One"
    2 -> "Two"
    3 -> "Three"
    else -> "Unknown"
}

println(label)

This is very common in Kotlin because it keeps code concise and readable.

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

  1. number is assigned the value 2.
  2. The when block checks number.
  3. Kotlin compares number with the first branch value: 1.
  4. 2 == 1 is false, so it moves to the next branch.
  5. Kotlin compares number with the second branch value: 2.
  6. 2 == 2 is true, so it runs:
println("Two")
  1. The output is:
Two
  1. The when block ends immediately after the matching branch. There is no fall-through and no need for break.

Important behavior

In Java, forgetting break can accidentally continue into the next case. In Kotlin, each when branch is isolated, so this mistake does not happen.

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("Show content")
    "error" -> println("Show error message")
    else -> println("Show empty state")
}

4. Processing user roles

val role = "admin"

when (role) {
    "admin" -> println("Full access")
    "editor" -> println("Edit access")
    "viewer" -> println("Read-only access")
    else -> println("No access")
}

5. Categorizing numeric values

val score = 85

when {
    score >= 90 -> println("Grade A")
    score >= 80 -> println("Grade B")
    score >= 70 -> println("Grade C")
    else -> println("Grade D")
}

This last example shows a second form of when that works without a subject value.

Take Quiz

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.

enum class Direction {
    NORTH, SOUTH, EAST, WEST
}

fun printDirection(direction: Direction) {
    when (direction) {
        Direction.NORTH -> println("Up")
        Direction.SOUTH -> println("Down")
        Direction.EAST -> println("Right")
        Direction.WEST -> println("Left")
    }
}

4. Using when instead of long if/else if chains

val fileType = "json"

when (fileType) {
    "json" -> println("Parse JSON")
    "xml" -> println("Parse XML")
    "csv" -> println("Parse CSV")
    else -> println("Unsupported format")
}

5. Error and response handling

In APIs or services, when often maps result states to actions.

val responseCode = 500

when (responseCode) {
    200 -> println("Success")
    400 -> println("Bad request")
    500 -> println("Log server error")
    else -> println("Handle unexpected code")
}

Common Mistakes

1. Trying to use switch in Kotlin

Broken code:

switch (5) {
    case 1:
        println("One")
}

Why it fails:

  • Kotlin has no switch keyword.
  • Kotlin uses when instead.

Correct code:

when (5) {
    1 -> println("One")
}

2. Writing case and break

Broken code:

when (5) {
    case 1:
        println("One")
        break
}

Why it fails:

  • case is Java syntax, not Kotlin.
  • break is not needed in when branches.

Correct code:

when (5) {
    1 -> println("One")
}

3. Forgetting else when needed

If you use when as an expression, Kotlin often requires all cases to be covered.

Broken code:

val text = when (number) {
    1 -> "One"
    2 -> "Two"
}

Why it fails:

  • Kotlin cannot guarantee what value should be returned for other numbers.

Correct code:

val text = when (number) {
    1 -> "One"
    2 -> "Two"
    else -> "Other"
}

4. Expecting fall-through behavior

In Java, code can continue into the next case if break is missing. Kotlin does not do this.

when (2) {
    1 -> println("One")
    2 -> println("Two")
    3 -> println("Three")
}

This prints only:

Two

5. Using the wrong when form

Kotlin supports two styles:

  • when (value) { ... } for matching a subject
  • when { condition -> ... } for boolean conditions

Example of condition-based when:

val age = 20

when {
    age < 13 -> println("Child")
    age < 20 -> println("Teen")
    else -> println("Adult")
}

Comparisons

ConceptJava switchKotlin when
Keywordswitchwhen
Branch labelcasedirect value or condition
Default branchdefaultelse
Needs breakUsually yesNo
Fall-throughYes, unless stoppedNo
Can return a valueLimited in older Java styleYes, naturally
Can match conditionsNot directlyYes
Can match ranges/typesLimitedYes

when vs if/else

Use casePrefer
Two simple choicesif/else
Many exact valueswhen
Ranges or grouped conditionswhen
Complex boolean logic with only one or two branchesif/else

Subject-based vs condition-based when

when (number) {
    1 -> println("One")
    2 -> println("Two")
    else -> println("Other")
}

Use this when comparing one value against several options.

when {
    number < 0 -> println("Negative")
    number == 0 -> println("Zero")
    else -> println("Positive")
}

Use this when each branch is a full condition.

Take Quiz

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 switch.
  • Do not write case.
  • Do not write break.
  • Use else like Java's default.
  • when can be a statement or an expression.
  • If used as an expression, all cases must be covered.

Java to Kotlin mental conversion

  • switch -> when
  • case -> value before ->
  • default -> else
  • break -> not needed

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.

val result = when (x) {
    1 -> "A"
    else -> "B"
}

Can Kotlin when check conditions instead of fixed values?

Yes. You can use when without a subject.

when {
    x > 0 -> println("Positive")
    else -> println("Not positive")
}

When should I use when instead of if?

Use when when you have several possible branches and want clearer, more readable code.

Take Quiz

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 when block to handle at least three command values.
  • Print a different message for each supported command.
  • Include an else branch for unsupported values.
  • Keep the program runnable as a simple Kotlin console application.
Take Quiz

Keep learning

Related questions

View more