Basics

Kotlin Null Safety

Null Safety in Kotlin

Kotlin null safety uses ? and !! for safe nullable types.

Introduction to Null Safety in Kotlin

Kotlin's null safety feature is a powerful tool designed to eliminate the NullPointerException error, which is notorious in many programming languages. By distinguishing between nullable and non-nullable types, Kotlin helps developers write safer and more reliable code.

Nullable Types and the '?' Operator

In Kotlin, a variable cannot hold a null value by default. You must explicitly allow a variable to hold a null by using the ? operator. This operator indicates that a variable can hold either a value of its specified type or null.

The Non-Nullable Type

By default, types in Kotlin are non-nullable. Attempting to assign null to a non-nullable variable will result in a compilation error. This ensures that null values are handled explicitly.

Safe Calls with '?.' Operator

The safe call operator ?. is used to safely access the properties or methods of a nullable variable. If the variable is null, the expression will return null instead of throwing an exception.

Elvis Operator '?:'

Kotlin provides the Elvis operator ?: as a way to handle null values with a default value. If the expression on the left of the Elvis operator is not null, it returns the expression; otherwise, it returns the expression on the right.

The '!!' Operator for Non-Null Assertion

The non-null assertion operator !! is used to convert a nullable type to a non-nullable type, asserting that the variable is not null. If the variable is null, it throws a NullPointerException.

Conclusion

Understanding and utilizing Kotlin's null safety operators, such as ?, ?., ?:, and !!, is essential for writing robust and error-free Kotlin code. By explicitly handling nullability, developers can prevent many common runtime errors related to null values.