Safe call operators 

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? = null
var 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 if condition, notice that Kotlin does not throw any errors. The if statement will be executed if the variable has a value, otherwise it will be skipped:

fun main(args: Array<String>) {
var name : String?
name = null // allowed
var length = 0
if(name != null && name.length > 0) {
length = name.length
}
}

In this example, we have declared a nullable string variable name and assigned a null to it. Later, we check if the name string variable is not null and length of the name variable is not zero. In this case, an if statement will skip the code block because name is assigned with null.

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

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