Search code examples
androidkotlinconditional-statements

Non-Exhaustive Error in When-Expression for a Sealed Class


I'm so stunned that I am getting a Non-Exhaustive Error when using a sealed classes with when-block.

This is the code that I am working with:

sealed class Vehicle

data class Car(val manufacturer: String, val model: String
) : Vehicle()

data class Bicycle(
    val manufacturer: String
) : Vehicle()

fun getVehicle(vehicle: Vehicle) =
    when (vehicle) {
        is Car -> "${vehicle.manufacturer} - ${vehicle.model}"
        is Bicycle -> vehicle.manufacturer
        
        //Error
        //'when' expression must be exhaustive, add necessary 'else' branch
    }

This is the error I am getting.

enter image description here

I have counter-checked with the latest V1.8.22 docs which clearly state the following:

if when is used as an expression, the else branch is mandatory, unless the compiler can prove that all possible cases are covered with branch conditions, for example, with enum class entries and sealed class subtypes).

I am of the view that all direct subclasses of a sealed class are known at the compile time and thus all outcomes on the when-expression are accounted for.

It is not a big deal to add the else-block but this comes as a shocker to me. I will appreciate your understanding on this.


Solution

  • The code as you posted it compiles without errors. You probably have another Vehicle subclass floating around somewhere. You can find it either by selecting Vehicle and using the Hierarchy view (Ctrl-H on my setup) or by selecting the when and pressing Alt-Enter -> Add remaining branches.