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
Kotlin has a safe call operator (?.) to handle null references. This operator executes any action only when the reference has a non-null value. Otherwise, it returns a null value. The safe call operator combines a null check along with a method call in a single expression.
Kotlin Null Safety NullPointerException can just only possible on following situations: Throw NullPointerException() as a forceful call. Using external java code as Kotlin, which means Java interoperability. An uninitialized of this operator that is available in a constructor passed and used another place.
Exception for of isEmpty() in JavaThe isEmpty() method throws a NullPointerException when the string is initialized to null.
java.lang.NullPointerException. Thrown when an application attempts to use null in a case where an object is required. These include: Calling the instance method of a null object. Accessing or modifying the field of a null object.
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
}<!>
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With