October 2018
Intermediate to advanced
370 pages
9h 15m
English
The safe call operator executes the called function if a variable contains a value. If not, it will return null. This is demonstrated as follows:
var mayBeNull : String? = null var length = mayBeNull?.length
If the length variable has a null value, we again need to verify whether the variable length is null or not. In this case, we may be stuck in an unnecessary verification loop. This problem can be solved by using the Elvis operator. The Elvis operator makes sure that one out of two values must be returned:
var length = mayBeNull?.length ? : 0
If length is not null, it will return the size of the variable; otherwise, it returns 0. See the following example:
fun main(args: Array<String>) { var message: String? = null ...Read now
Unlock full access