Kotlin compiler not warning about potential null pointer exception
I have this simple kotlin snipped that tries to map list elements to strings like this:
sealed class MySealedClass
class MyClass1 : MySealedClass()
class MyClass2 : MySealedClass()
fun doTheMapThing(elements: List<MySealedClass>): List<String> {
return elements.flatMap {
when (it) {
is MyClass1 -> listOf("Yeah")
is MyClass2 -> null
}
}
}
In the flatMap
, the when
either maps to a list or to null
, so the effective return type of the when
is List<String>?
. I was a bit surprised to see this compiling without any issues. Shouldn't the kotlin compiler warn about this? When I extract the when
to a function, I get a proper compiler error. Am I missing something here or could this be a bug?
Using kotlin 1.5.31
Solution 1:
Just for completeness: It was a bug. The fix will be released with Kotlin 1.7.0
. More details on that can be found here: https://youtrack.jetbrains.com/issue/KT-49658
If you're interested in even more details, you can find the actual fix here: https://github.com/JetBrains/kotlin/commit/37d163d417bfe8ecd2e4baea3e5651906c96e150
A nice thing is that our example actually made it into the test code for kotlin:
fun doTheMapThing1(elements: List<CharSequence>): List<String> {
return elements.flatMap {
<!TYPE_MISMATCH_WARNING!>when (it) { // NullPointerException
is String -> listOf("Yeah")
else -> null
}<!>
}
}