Null Safety Features
Stryg for at vise menuen
Kotlin provides robust null safety features to help you avoid the common pitfalls of working with nullable types. The most important tools for handling nullable values are safe calls, the Elvis operator, and the not-null assertion operator (!!). These features let you safely access properties and methods on variables that might be null, provide default values when needed, and handle cases where you are certain a value is not null. Understanding how and when to use each feature is essential for writing reliable Kotlin code.
Main.kt
123456789101112131415161718192021package com.example fun main() { val name: String? = null // Safe call: returns null if 'name' is null, otherwise calls 'length' val lengthSafe = name?.length println("Safe call result: $lengthSafe") // Output: Safe call result: null // Elvis operator: provides a default value if 'name' is null val lengthElvis = name?.length ?: 0 println("Elvis operator result: $lengthElvis") // Output: Elvis operator result: 0 // Not-null assertion (!!): throws an exception if 'name' is null try { val lengthAssert = name!!.length println("Not-null assertion result: $lengthAssert") } catch (e: NullPointerException) { println("Not-null assertion threw an exception: ${e::class.simpleName}") } }
You have seen how each null safety feature behaves in practice. The safe call operator (?.) is ideal when you want to safely access a property or method on a nullable variable and are comfortable with the result being null if the variable itself is null. The Elvis operator (?:) is useful when you want to provide a default value in case the expression to the left is null, making your code more predictable and avoiding null-related crashes. The not-null assertion operator (!!) should be used sparingly and only when you are absolutely certain that a nullable variable is not null at that point in your code; otherwise, it will throw a NullPointerException and crash your program. Choose the feature that best matches your intent and the guarantees you have about your data.
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat