javakotlinnullpointerexceptionkotlin-null-safety

How can I safely handle null values when calling Java methods from Kotlin?


How can I handle null safety in Kotlin when interfacing with Java libraries that do not have null safety?

Through research, here are things I found that "work", but are not safe.

  1. Using Kotlin's non-null type with a Java method that returns null:

  2. Using !! operator with a Java method that returns null:

  3. Assuming a Java Boolean is never null: In Java, Boolean can be true, false, or null, but in Kotlin, Boolean can only be true or false.

In these examples, my Kotlin compiler won't show an error because it doesn't have enough information about whether the Java methods can return null.


Solution

  • Treat it the same way you would in Java. Assume the value might be null unless the documentation for the method that you are getting it from declares that it will not be null. If it does not declare that it will not return null, it is nullable. Treat it exactly as a nullable Kotlin variable. So use ?., ?:, if (foo != null), or .orEmpty() as appropriate for the situation.

    Java also has non-nullable boolean, long, int, char, byte, double, and float. If you see the lowercase type, you know it's not nullable.