Sobes.tech
Junior

How should null values be checked in code?

sobes.tech AI

Answer from AI

The following approaches are used in Kotlin for working with nullable types and null checks:

  1. Safe call operator (?.): Allows calling methods or accessing properties of an object only if the object is not null. If the object is null, the entire call returns null.

  2. Elvis operator (?:): Provides a default value if the expression on the left of the operator is null.

  3. Unsafe call operator (!!): Converts a nullable type to a non-nullable type. If the value is null, a NullPointerException is thrown. Its use is highly discouraged as it can cause the application to crash.

  4. if block with null check: A traditional way of checking, often used in conjunction with Kotlin's smart casts.

// Safe call operator ?.
val length = text?.length

// Smart cast after null check
if (text != null) {
    val length = text.length // text is automatically cast to String (non-nullable)
}

// Elvis operator ?:
val nonNullText = text ?: "Default Text"

// Unsafe call operator !! (avoid if possible)
val forceLength = text!!.length // May throw NullPointerException

In Java, null checks are performed exclusively using conditional if statements:

// Java
if (text != null) {
    int length = text.length();
} else {
    // Handling case when text is null
}