Sobes.tech
Junior

What are 'nullable' types in Kotlin and how do they work?

sobes.tech AI

Answer from AI

Nullable types in Kotlin are types that can hold either a value or null. They are explicitly marked with a ? after the type name.

The operation is based on Kotlin's type system, which prevents NullPointerException at compile time. The compiler requires an explicit null check before accessing members of a nullable object.

Main ways to safely work with nullable types:

  • Null check using if:

    fun printLength(str: String?) {
        if (str != null) {
            println(str.length) // Safe call after null check
        } else {
            println("String is null")
        }
    }
    
  • Safe call operator (?.): Returns null if the object is null, otherwise the result of the call.

    val safeLength: Int? = str?.length // If str is null, safeLength will be null
    
  • Elvis operator (?:): Provides a default value if the expression on the left is null.

    val lengthOrDefault: Int = str?.length ?: 0 // If str is null, lengthOrDefault will be 0
    
  • Not-null assertion operator (!!): Converts a nullable type to a non-nullable one. Use with caution, as it will throw a NullPointerException if the value is null.

    val assertedLength: Int = str!!.length // Will throw NPE if str is null
    
  • let/run/apply/also functions with safe call:

    str?.let {
        // Code executes only if str is not null
        println("String length: ${it.length}")
    }
    

Kotlin's nullable type system significantly enhances safety and reduces the likelihood of NullPointerException compared to languages where null can be assigned to any type without explicit notation.

What are 'nullable' types in Kotlin and how do they… - sobes.tech