Sobes.tech
Junior

Mis on 'nullable' tüübid Kotlinis ja kuidas nad toimivad?

sobes.tech AI

Vastus AI-lt

Nullable types in Kotlin are types that can hold either a value or null. They are explicitly marked with a ? symbol 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 type.

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
    
  • Explicit not-null assertion operator (!!): Converts a nullable type to a non-nullable type. 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 indication.