Kotlin Platform Types

I was coding my own business till my colleague suddenly poked me on the shoulder. He said that he had a crash in his code but couldn’t figure out where. I looked at his screen and checked his code but everything seemed alright to me. So I continued my tasks and he went in investigation-mode.

a few hours later

Again I was poked on my shoulder, but this time I saw my colleague crying with joy. He found out what the issue was and wanted to share it with me.

What we saw was that when invoking Java code from Kotlin it is sometimes unknown if the type is Nullable. For example a getter could be called that that has no @Nullable or @NonNull annotation. That type is called a platform type, sometimes denoted by an exclamation mark. E.g. String! for the platform String type.

The current version of the Kotlin compiler hopes for the best and allows the platform type to be treated as non-null. Sometimes that hope is shattered by an IllegalStateExceptions when at runtime the assumed value is null.

An example of this issue is shown below.

This method made in Kotlin invokes a Java method that returns a nullable string. In this case the method always returns null, but Kotlin treats it as non-null.

source: https://kotlinlang.org/docs/reference/java-interop.html

Best fix is to add the @Nullable or @NonNull annotation so that the compiler knows the nullability and you can handle the code correctly.

Another colleague of mine made a small plugin to discover platform types in your IDE. You can see his project here:

source: https://github.com/rcgroot/skullbones

Also check out the Kotlin inspection, it will give out a weak warning when using platform types.


Add a Comment

Your email address will not be published. Required fields are marked *