Avoiding NullpointerException with Java Objects to Kotlin
Kotlin is null-safe, a quote I hear often from Kotlin developer.
And yet, I still managed to get a NullPointerException while converting a java.util.Optional
to a nullable Kotlin value…
How did it occur?
The reason this happened was due to an external java class which contains an Optional, which I assumed is never null but either filled with a value or empty. But for example if you use the FasterXML/Jackson library how to deal with missing fields and Optionals in the json is a choice in configuration. So if in the JSON the field is null or empty due to some configuration, your Optional could or could not be null/empty.
An example:
val myJavaObject = MyJavaObject(); //contains field Optional<String> `value` = null
val optionalValue : String? = myJavaObject.value.getOrNull() // map the Optional to an kotlin nullable String
//Result: java.lang.NullPointerException: getValue(...) must not be null
How to avoid this?
To ensure this never happens anymore to me I have imprinted 'in Java, if it theoretically could be null then someday it will be null'. From now on I will be better:
val myJavaObject = MyJavaObject(); //contains field Optional<String> `value` = null
val optionalValue : String? = myJavaObject.value?.getOrNull() // map the Optional to an kotlin nullable String
//Result: optionalValue = null