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?