Android | Kotlin | NULL SAFETY

Kotlin | NULL SAFETY


Elvis Operator:  ?:

x ?: y ---- evaluates x, 

If x!=null,

Then the result of the expression = x

  Else 

         Result of expression = y    //(which ought to be of a non-nullable type)

We can also use this operator to perform an early return in case of null:

Example :

val z = x ?: return y

 Explanation:

    If x!=null

       Assign x to z

   Else

       the entire function that contains this expression will stop and return y.

      (this works because return is also an expression, and if it is evaluated, it evaluates its argument and then makes the containing function return the result).


Safe call operator:   (?.)

x?.y  -- evaluates x,

Explanation:

If x!=null

     Evaluate x.y  (without reevaluating x) & the result becomes the result of expression.

Else

   We will get null.


This also works for functions, and it can be chained as well.

Example:

a?.f1()?.b?.f2() will return null if any of a, a.f1(), or a.f1().b produce null; otherwise, it will return the result of a.f1().b.f2().


Not-null assertion operator (!!)

This operator converts any value into a non-null type & throws NullPointerException if the given value is null.

This operator is helpful if you want to perform some specific operation in case of NULL value.

Unlike the other operators for Null Safety, the not-null assertion operator deliberately throws NullPointerException for null values.


Example:

var str1 :String? = "Kotlin"

var str2 :String? = null

println("length = ${str1!!.length} ")    //o/p : length = 6

println("length = ${str2!!.length} ")    // NullPointerException



Comments

Post a Comment

Popular posts from this blog

Android | Android Context | Different Types Of Context | Application Context | Activity Context | getContext()