Tom De Decker
05/23/2023, 1:05 PMsealed interface Base {
data class Foo(val foo: String) : Base
data class Bar(val bar: String) : Base
data class Baz(val baz: String) : Base
}
fun doThing(thing: Base) {
if (thing is Base.Foo || thing is Base.Bar) {
when (thing) {
is Base.Foo -> thing.foo
is Base.Bar -> thing.bar
// Error: When expression must be exhaustive
}
}
}Sam
05/23/2023, 1:12 PMwhen block itself. The if statement doesn’t participate in the exhaustiveness check. It could narrow the type via a smart cast, but unfortunately the common supertype of Base.Foo and Base.Bar is still Base, so there’s nothing to narrow it to.Sam
05/23/2023, 1:13 PMwhen block has to cover all possible values of the type of its subject. And the compile-time type of the when subject is Base.Sam
05/23/2023, 1:13 PMTom De Decker
05/23/2023, 1:14 PMspleenjack
05/23/2023, 2:13 PMStephan Schröder
05/23/2023, 2:51 PMwhen now exhaustive even if it's a statement!?Sam
05/23/2023, 2:56 PM