Skip to content
Latchkey

Kotlin "incompatible types" in when expression in CI

A when used as an expression either has branches returning incompatible types, or is not exhaustive over the subject. The compiler cannot give the whole expression a single type.

What this error means

The build fails with incompatible types across when branches, or 'when' expression must be exhaustive, add necessary else branch. It is deterministic.

gradle
e: file:///src/main/kotlin/App.kt:10:18 'when' expression must be
exhaustive, add necessary 'is Error' branch or 'else' branch instead

Common causes

Non-exhaustive when used as expression

A when over a sealed class or enum missing a case cannot be used as an expression without an else.

Branches return unrelated types

Different branches yield types with no useful common supertype, so the result type is too wide or invalid for its use.

How to fix it

Cover every case

Handle all sealed/enum cases (or add else) so the when is exhaustive.

App.kt
val msg = when (result) {
  is Ok -> result.value
  is Error -> result.reason
}

Align branch result types

  1. Make each branch produce the same expected type.
  2. Annotate the target type so mismatches are flagged early.
  3. Prefer sealed classes so the compiler enforces exhaustiveness.

How to prevent it

  • Use sealed classes for exhaustive when checks.
  • Annotate the expected result type.
  • Keep branch return types consistent.

Frequently asked questions

What causes ""'when' expression ... incompatible types""?
A when over a sealed class or enum missing a case cannot be used as an expression without an else.
How do I fix "'when' expression ... incompatible types"?
Handle all sealed/enum cases (or add else) so the when is exhaustive.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card