Explain Safe call, Elvis and Not Null Assertion operator in the context of Kotlin.
Safe Call operator ( ?. ) - Null comparisons are trivial, but the number of nested if-else expressions can be exhausting. So, in Kotlin, there\'s a Safe call operator,?, that simplifies things by only doing an action when a specified reference holds a non-null value. It allows us to use a single expression to perform both a null check and a method call.
For example,
The following expression in Kotlin
name?.toLowerCase() is equivalent to the following
if(name != null)
name.toLowerCase()
else
null Elvis Operator ( ?: ) - When the original variable is null, the Elvis operator is used to return a non-null value or a default value. In other words, the elvis operator returns the left expression if it is not null, otherwise, it yields the right expression. Only if the left-hand side expression is null is the right-hand side evaluated.
For example,
The following expression in Kotlin
val sample1 = sample2 ?: "Undefined"is equivalent to the following
val sample1 = if(sample2 != null)
sample2
else
"Undefined"Furthermore, on the right side of the Elvis operator, we may use throw and return expressions, which is particularly handy in functions. As a result, instead of returning a default value on the right side of the Elvis operator, we can throw an exception. For example,
val sample1 = sample2 ?: throw IllegalArgumentException("Invalid")Not Null Assertion Operator ( !! ) - If the value is null, the not null assertion (!!) operator changes it to a non-null type and throws an exception.
Anyone who wants a NullPointerException can ask for it explicitly with this operator.
For example,
// KOTLIN
fun main(args: Array) {
var sample : String? = null
str!!.length
}The above code snippet gives the following output:-
Exception in thread "main" kotlin.KotlinNullPointerExceptionEnregistrer pour revision
Enregistrer pour revision
Ajoutez cet element aux favoris, marquez-le comme difficile ou placez-le dans un ensemble de revision.
Connectez-vous pour enregistrer des favoris, des questions difficiles et des ensembles de revision.