I suspect there might be a bug with the Kotlin compiler when it comes to sealed classes and the when
keyword. I found two things.
Arbitrary sealed classes in ‘when’ clause
This is the content of a kt file:
sealed class SealedA {
data class SubA(val value: String): SealedA()
data class SubB(val value: String): SealedA()
}
fun awesomeFunc(obj: SealedA): Unit = when(obj) {
is SealedA.SubA -> TODO()
is SealedA.SubB -> TODO()
}
Everything is fine so far.
This is the content of an other file:
sealed class Crap {
}
Now if I modify awesomeFunc
and add Crap
to the when clause, I expect a compile error because it can never be true. Result after modification:
fun awesomeFunc(obj: SealedA): Unit = when(obj) {
is SealedA.SubA -> TODO()
is SealedA.SubB -> TODO()
is Crap -> TODO() //Should give compile error since this can never be true
}
Matter fact, I can put any sealed class as an option to the when clause and it will work.
To many sealed classes in a file?
This one is harder to reproduce. I had multiple sealed classes in a file. Whenever I added an instance of one of them to a when
statement, the compiler insisted I added an else
branch. I fixed the problem by moving the sealed class to a new file.