Null Safety in Kotlin


Null Safety in Kotlin

Kotlin Null Safety is a procedure to eliminate the risk of invalid references from the code. The Kotlin compiler throws NullPointerException as soon as it finds any empty argument. The Kotlin type system is intended to be excluded from the code NullPointerException.

The possible causes of NullPointerExceptions are:

  • Throw NullPointerException to explicit call.
  • With the use of!! Operator.
  • Some data inconsistencies regarding startup, e.g., an uninitiated it, are passed as an argument.
  • Java interoperability, such as attempts to access a member with invalid references, is a generics type with incorrect nullability.

Nullable and Non-Nullable types

The Kotlin type system distinguishes between two types of references: Nullable references that can hold null values and Non-Nullable references, string variables that cannot store null values. If we try to enter a null into the variable, it returns a compiler error.

Safe Call Operator (?.)

The null comparisons are simple, but the number of nested expressions, whether nested or not, can be overwhelming. So, the code has a secure call operator, ?. It minimizes this complexity and only executes an action when the specified reference has a non-null value. This allows us to combine a null-check and a method call into a single expression.

If the value is not null, we can use the secure call operators such as let (), also (), and run ().

Let () Method – It is used to execute an action only if a reference holds a non-Nullable value; we can use a let () operator. To implement Lambdas expression within the letter only if the first name is not null.

Also () method chain with let() – If we want to apply some additional functionality, such as printing invalid items on the list, we can use the also () method and a let () or run ().

Run () method - Kotlin has a run () to execute certain operations on an invalid reference. This looks very similar to let (), but the run () method only works when this reference is used instead of a function parameter inside a function body.

Elvis Operator (? :)

The Elvis operator assigns a non-null value or a default value when the original variable is invalid. In other words, if the left expression is invalid, the Elvis operator returns it; otherwise, it returns the correct expression. The expression on the right will be evaluated only if the left side is found to be empty.

Moreover, on the right side of the Elvis operator, we can also use throw and return expressions, which are very useful in functions. Therefore, we can give an exception instead of providing the default value to the right of the Elvis operator.

Not null assertion: !! Operator - The operator converts any value to a non-null type and grants an exception if the value is invalid. If anyone wants NullPointerException, they can ask clearly with this operator.