1.

Explain Safe call, Elvis and Not Null Assertion operator in the context of Kotlin.

Answer»

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,

// KOTLINfun main(args: Array<String>) { var sample : String? = null str!!.length}

The above CODE snippet gives the following OUTPUT:-

Exception in THREAD "main" kotlin.KotlinNullPointerException


Discussion

No Comment Found