The ?: Elvis operator

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

var len = message?.length ?: 0
println("value of length is $len")

message = "Hello"
len = message?.length ?: 0

println("value of length is $len")
}

Create a nullable string variable called message and assign a null value to it. Use the Elvis operator, call the length function, and verify the value of the len variable, which should be 0. Now assign a value to message and verify the length.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.172.38