How to ensure null safety in kotlin
By using the certain methods and operator
Safe Call operator(?.) It will print null value in case if the data is null otherwise perform mentioned operation if the data is not null.
var obj:String? = null
println(obj.length) // show compile time errorOnly safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?
in order to avoid this we will be calling ?. operator after the variable name
println(obj?.length)
Now the output will be null since the value for the variable is not defined and by default we declared null to the string.
Safe Call operator(?.) with let function
It will perform operation only when it is not null other it wont execute the loop
var obj:String? = null
val ob = obj?.let {
println("Values is "+obj?.length)
}
it wont execute the loop since the value for obj is null
var obj:String? = "Pandiyan
val ob = obj?.let {
println("Values is "+obj?.length)
}
output is 8 because the value is not null so it will execute the let function
By other scope function also we can use safe call operator
Elvis Operator(?:)
In case of null it will return default value
var obj:String? = null
val obj = obj?.length ?: "Its null"OUTPUT is :
Its nullvar obj:String? = "HI
val obj = obj?.length ?: "Its null"OUTPUT is :
2
Not null assertion : !! Operator
Use it when you are sure the value wont be not null otherwise it will throw kotlin null pointer exception.
var obj:String? = null
println("Values is "+obj!!.length)//it will throw java.lang.NullPointerException
If its not null it will print the actual value