Home > OS >  What are nullable rules when calling Java from Kotlin
What are nullable rules when calling Java from Kotlin

Time:06-03

Why does Kotlin in one case infer type returned from Java to be nullable and in another case it is can be either, nullable or non-nullable?

I've checked both HashMap.get and JsonNode.get and I could not identify any @NotNull-like annotations neither in calsses nor anywhere in inheritance chain. What makes Kotlin treating those 2 calls differently?

I have read documentation code that uses java.util.Map with an IntelliJ warning: This class shouldn't be used in Kotlin. Use kotlin.collections.Map or kotlin.collections.MutableMap instead.

So if we look at the code for the get function that kotlin.collections.Map defines, enter image description here

  • Select 'Nullable' annotation

    enter image description here

  • Save annotations.xml

  • Now node.get("") will show an warning.

    enter image description here

    This annotation isn't visible to the Kotlin compiler, so it can only be a warning - not a compilation error.

    CodePudding user response:

    java.util.HashMap.get implements the interface method java.util.Map.get. Kotlin maps some Java types to its own types internally. The full table of these mappings is available on the website. In our particular case, we see that java.util.Map gets mapped internally to kotlin.collections.Map, whose get function looks like

    abstract operator fun get(key: K): V?
    

    So as far as Kotlin is concerned, java.util.Map is just a funny name for kotlin.collections.Map, and all of the methods on java.util.Map actually have the signatures of the corresponding ones from kotlin.collections.Map (which are basically the same except with correct null annotations).

    So while the first two node.get calls are Java calls and return platform types, the third one (as far as Kotlin is concerned) is actually calling a method Kotlin understands: namely, get from its own Map type. And that type has an explicit nullability annotation already available, so Kotlin can confidently say that that value can be null and needs to be checked.

    • Related