A nullable variable also cannot be used to call a function or to access a property in the usual way. Earlier in this chapter the toUpperCase() function was called on a String object. Given the possibility that this could cause a function to be called on a null reference, the following code will be disallowed by the compiler:
val username: String? = null
val uppercase = username.toUpperCase()
The exact error message generated by the compiler in this situation reads as follows:
Error: (Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?
In this instance, the compiler is essentially refusing to allow the function call to be made because no attempt has been made to verify that the variable is non-null. One way around this is to add some code to verify that something other than null value has been assigned to the variable prior to making the function call:
if (username != null) {
...