Sling Academy
Home/Kotlin/Kotlin: Missing `when` Branch Error

Kotlin: Missing `when` Branch Error

Last updated: December 01, 2024

In Kotlin, one of the most powerful constructs for handling control flow is the when expression. It's Kotlin's way of replacing the traditional switch statement found in other languages like Java, but with more flexibility and power. However, sometimes users encounter the 'Missing when branch' error. This article explains why this error occurs and how to resolve it.

Understanding the when Expression

The when expression in Kotlin allows you to branch your code execution based on a value. It's very much like a series of if-else statements but more readable and concise. The basic syntax is as follows:


val result = when (x) {
    1 -> "one"
    2 -> "two"
    else -> "unknown"
}

Here, x is evaluated, and if it matches one of the specified values (1 or 2), the corresponding code block is executed. If no match is found, the else branch is executed.

Why the 'Missing when Branch' Error Occurs

This error typically arises when you're using the when expression with an enum class or sealed class without handling all possible cases. Kotlin expects you to cover all possible branches to satisfy exhaustiveness, which ensures that all potential inputs are handled, reducing the likelihood of runtime errors.

Example with Enum

Consider the following example with enums:


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

fun getDirectionDescription(direction: Direction): String {
    return when (direction) {
        Direction.NORTH -> "Top"
        Direction.SOUTH -> "Bottom"
        Direction.EAST  -> "Right"
        // Direction.WEST is missing
    }
}

The above code will raise a 'Missing when branch' error because the WEST direction is not handled.

Example with Sealed Class

Similarly, consider a sealed class scenario:


sealed class Expression {
    class Const(val number: Double) : Expression()
    class Sum(val e1: Expression, val e2: Expression) : Expression()
    object NotANumber : Expression()
}

fun eval(expr: Expression): Double = when(expr) {
    is Expression.Const -> expr.number
    is Expression.Sum -> eval(expr.e1) + eval(expr.e2)
    // Expression.NotANumber is missing
}

This code snippet will also raise the 'Missing when branch' error due to the unhandled Expression.NotANumber.

How to Fix the Error

There are a couple of ways to fix this error:

  1. Handle All Branches: The best way to resolve this error is to explicitly handle all possible cases in your when expression.
  2. Add an else Branch: If it's impractical to handle every case individually, you can add a general else branch to ensure all paths are covered.

Comprehensive Example Solution

Here is a corrected version of the previous enum example that handles all branches:


fun getDirectionDescription(direction: Direction): String {
    return when (direction) {
        Direction.NORTH -> "Top"
        Direction.SOUTH -> "Bottom"
        Direction.EAST  -> "Right"
        Direction.WEST  -> "Left" // Now, WEST is handled
    }
}

This ensures all enum constants are covered, and the error is resolved.

Conclusion

Handling control flow with the when expression in Kotlin is elegant and powerful, but developers must be mindful of covering all potential branches, especially when dealing with enums and sealed classes. By understanding the 'Missing when branch' error and knowing how to fix it, you can write more robust and safe Kotlin code.

Next Article: Kotlin: Modifier `open` Required Error

Previous Article: Kotlin: Property Must Be Initialized or Be Nullable

Series: Common Errors in Kotlin and How to Fix Them

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin