October 2018
Intermediate to advanced
370 pages
9h 15m
English
Now we are able to declare a nullable type, but what if we try to get a length of a string that is nullable? See the following example:
var mayBeNull : String? = nullvar length = mayBeNull.length
Kotlin null safety will trigger the following error:
Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?
In simple terms, a programmer will be notified that the declared variable (string in this case) can have a null value, and this must be verified before calling. It can be validated in different ways, but one way of doing this is by using an if statement:
var mayBeNull : String? = null if(mayBeNull != null && mayBeNull.length > 0){ var length = mayBeNull.length }
Within the
Read now
Unlock full access