Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Null Safety Features | Nullable and Special Types
Kotlin Data Types

bookNull Safety Features

Scorri per mostrare il menu

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

Main.kt

copy
123456789101112131415161718192021
package 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.

question mark

What does the '!!' operator do when used with a nullable variable?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 3. Capitolo 2

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 3. Capitolo 2
some-alt