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

bookNullable Types

Glissez pour afficher le menu

Kotlin introduces a powerful approach to handling null values, which helps you avoid one of the most common errors in programming: the null pointer exception. In Kotlin, every variable must explicitly state whether it can hold a null value. By default, variables are non-nullable, meaning they cannot be assigned null. If you want a variable to be able to store null, you must declare it as a nullable type by appending a question mark (?) to its type. This design enforces safer code and reduces runtime errors related to null values.

Main.kt

Main.kt

copy
12345678910111213141516171819
package com.example fun main() { val nonNullableString: String = "Hello, Kotlin!" // The following line would cause a compile-time error: // nonNullableString = null val nullableString: String? = null println("Non-nullable: $nonNullableString") println("Nullable: $nullableString") // Safe call operator usage println("Length of nullable string: ${nullableString?.length}") // Elvis operator usage val lengthOrZero = nullableString?.length ?: 0 println("Length or zero: $lengthOrZero") }

In the code above, you see both non-nullable and nullable variable declarations. The variable nonNullableString cannot be assigned null, so attempting to do so would result in a compile-time error. The variable nullableString, declared with the String? type, can safely store a null value.

To access properties or methods of a nullable variable, you use the safe call operator (?.). This operator allows you to call a method or access a property only if the variable is not null, otherwise it returns null. For example, nullableString?.length will return the length if nullableString is not null, or null if it is.

When you want to provide a default value in case the variable is null, you use the Elvis operator (?:). This operator evaluates the expression on its left; if it is not null, that value is returned. If it is null, the expression on the right is used instead. In the example, nullableString?.length ?: 0 will return the length of the string if it is not null, or 0 if it is.

question mark

What symbol is used to declare a nullable type in Kotlin?

Select the correct answer

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 3. Chapitre 1

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

Section 3. Chapitre 1
some-alt