Forcing platform type to always nullable?


Is there a reason why platform type can be assigned to non nullable variables?

This is because as platform type can be null, the null safety principle of Kotlin should be 'force user to check platform type by default to prevent null error. Instead, if we forget to check, we may have a null exception.

Suppose getLocationService don’t have a nullable annotation, so the compiler can’t tell.

If we write
var location = getLocationService()
We may have a null exception! Even the compiler won’t tell us to do the check!

If we want to be careful, we need to do this:
var location: LocationService? = getLocationService()
We need to know that the result of this function is a ‘maybe nullable’ platform type and also know the result type to be able to specify the question mark… This is a lot of work/knowledge to prevent us from null exception. If we forget, the exception may

If the default was to ‘force’ nullable variable, this would mean that
var location = getLocationService()
will not compile. It would be interesting to have a shortcut as maybe
var location? = getLocationService()
to force us to realize this may be null and check it before going further with this result!

In my opinion, T! should never have meant T or T? as in the doc. What should be really useful would be to change this (maybe breaking change) or have a parameter (like experimental) to force T! to always be T?. And with a new definition shortcut, this will ease all variable definition.

What do you think about this?


A lot of functions (I guess, majority of them) use non-null conventions. If they were exposed to Kotlin as nullable parameters/return values, Kotlin code would be full of “!!” operators or meaningless checks. IMHO better solution would be to add external annotations for Java bytecode and some bytecode-processing tool which would guess a lot of null/not null annotations. Typescript demonstrates that community can add typings to existing libraries and this approach works. Of course it could be done in the future, so may be it’ll be done.


This talk by Andrey Breslav explains in detail why platform types are not, and are not going to be, always nullable: