Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin compiler not warning about potential null pointer exception

Tags:

kotlin

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

like image 739
Jan Gassen Avatar asked Nov 11 '21 10:11

Jan Gassen


People also ask

How does kotlin handle the null exception?

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.

Can we throw NullPointerException in Kotlin?

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.

Does isEmpty throw NullPointerException?

Exception for of isEmpty() in JavaThe isEmpty() method throws a NullPointerException when the string is initialized to null.

What is NullPointerException Kotlin?

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.


1 Answers

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
        }<!>
    }
}
like image 152
Jan Gassen Avatar answered Oct 26 '22 07:10

Jan Gassen