Photo by Caspar Camille Rubin on Unsplash

In Kotlin, variables are declared by keyword val and var. There is much care has been taken to reduce NullPointerException. There are two type systems that can hold a null value or not. A regular variable type can NOT hold null value.

To store a null value, variable needs to be declared nullable as String?

Safe Call ?.

To access nullable variables, we use Safe Call. If variable is not null, it will execute the right side of ?. operator. If variable is null it will not execute right side (returns null) and does not throw NullPointerException.

Elvis Operator ?:

It is more useful operator than safe-call operator. It is same as ternary operator. If variable is null then safe-call will return null only. Using Elvis operator, expression can return anything including null.

Since ‘throw’ and ‘return’ are expressions, they can be used on the right side of Elvis operator.

!! Operator

There is another operator which will evaluate variable, if not null, otherwise throws NullPointerException. So, if you are confident that variable will not be null, then only use !! operator.

Kotlin worked to eliminate crashing application due to NullPointerException. It is always good practice to use safe-call or elvis operator to reduce the accident.

Thank You :)

Android l Kotlin l Java | https://kiranpande1987.github.io/