https://kotlinlang.org logo
Title
g

ghosalmartin

04/21/2022, 7:40 AM
Noticed this warning today,
Non exhaustive 'when' statements on sealed class/interface will be prohibited in 1.7, add 'else' branch
Does that mean using a sealed class/interface will no longer be exhaustive in a
when
. I thought that was a feature of ``sealed`?
e

ephemient

04/21/2022, 8:17 AM
you need to explicitly match everything or add
else
r

Roukanken

04/21/2022, 8:18 AM
currently in
when
statements, you don't need else - there is an implicit "else -> do nothing" in statements (when's without return value) in 1.7 this will no longer be case, and you'll need to add the else clause even in statements
e

ephemient

04/21/2022, 8:20 AM
there is still an implicit "else -> do nothing" for non-sealed non-enum types
r

Roukanken

04/21/2022, 8:20 AM
and yeah, this is only a topic when we're talking about sealed/enums
g

ghosalmartin

04/21/2022, 9:03 AM
hmm okays but what about if am attaching the result of a
when
to a variable and the switching type is a sealed
r

Roukanken

04/21/2022, 9:05 AM
in that case, then even in current version you need to list all the cases OR use an else the 1.7 change is just, that it will work the same way even if you are not using the result of the when
e

ephemient

04/21/2022, 9:19 AM
exactly. if the value is used, the
when
must be exhaustive, always - either by having full branch coverage or by
else
, regardless of the type. if the value is not used, previously Kotlin did not enforce exhaustive
when
, but for enums and sealed types it will.
r

Richard Gomez

04/21/2022, 11:25 PM
@ghosalmartin What does your code look like? I ran into a strange issue last week with a
when
block and a `sealed interface.`It forced me to add an
else
statement despite having all the cases defined.
g

ghosalmartin

04/22/2022, 8:14 AM
tbf this code is purely to flex the feature shall we say but
but this gives me the warning
sealed interface House {
    data class Semidetached(val sharedWall: String): House
    data class Detached(val noSharedWall: String): House
}

fun test(){
    val myHouse: House = House.Detached("")
    
    when(myHouse){
        is House.Detached -> myHouse.noSharedWall
        is House.Semidetached -> myHouse.sharedWall
    }
    
}
e

ephemient

04/22/2022, 11:00 AM
IDE or command-line compiler? there's a number of IJ plugin bugs around this, such as https://youtrack.jetbrains.com/issue/KTIJ-21016 https://youtrack.jetbrains.com/issue/KTIJ-21190
r

Richard Gomez

04/22/2022, 12:02 PM
IDE or command-line compiler? there's a number of IJ plugin bugs around this, such as
In my case it was the IDE. Good to know.