Sobes.tech
Junior

Explain what null safety is in Kotlin.

sobes.tech AI

Answer from AI

Null safety is a feature of the Kotlin language that prevents errors related to null references. It is achieved by creating two types of references: nullable (allowing null) and non-nullable (not allowing null).

Non-nullable types are declared as usual:

var nonNullableString: String = "Hello" // Cannot be null

Nullable types are declared using the ? symbol after the type name:

var nullableString: String? = "Hello" // Can be null
nullableString = null

Kotlin requires explicit handling of nullable types, preventing direct access to their members without a prior null check. The following mechanisms are provided:

  1. Safe call operator (?.): Calls a method or accesses a property only if the object is not null. Otherwise, it returns null.

    val length = nullableString?.length // length will be Int? or null
    
  2. Elvis operator (?:): Provides a default value if the expression on the left of the operator is null.

    val nonNullLength = nullableString?.length ?: 0 // nonNullLength will be Int, 0 if nullableString is null
    
  3. Not-null assertion operator (!!): Converts a nullable type to a non-nullable. If the value is null, a NullPointerException is thrown. Used when the developer is sure that the value is not null.

    val sureLength = nullableString!!.length // Will throw NullPointerException if nullableString is null
    
  4. if-checks: Traditional null check using if. The compiler smart casts nullable types to non-nullable inside the if block if the null check passes.

    if (nullableString != null) {
        val length = nullableString.length // Here nullableString is considered as String
    }
    

These mechanisms allow explicit management of situations where a variable can be null, significantly reducing the likelihood of NullPointerException during program execution.

Explain what null safety is in Kotlin. — Kotlin - sobes.tech