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.
e: file:///src/main/kotlin/App.kt:10:18 'when' expression must be
exhaustive, add necessary 'is Error' branch or 'else' branch insteadCommon 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.
val msg = when (result) {
is Ok -> result.value
is Error -> result.reason
}Align branch result types
- Make each branch produce the same expected type.
- Annotate the target type so mismatches are flagged early.
- 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.