Search⌘ K
AI Features

Nullable Types

Explore how Kotlin's type system manages nullable and non-nullable types to prevent null pointer exceptions. Understand how to safely access nullable objects using the safe call operator, apply default values with the Elvis operator, and when to cautiously use the unsafe call operator. This lesson equips you with essential tools to handle null values effectively and write safer Kotlin code.

Kotlin’s type system differentiates between nullable and non-nullable types. By default, types are non-nullable; you cannot get a null pointer exception from dereferencing it.

This is why Kotlin’s basic data types, such as Int, can map safely to Java’s primitive types, such as int, in the bytecode. Both can never be null.

Thus, all objects and types you’ve seen so far in this course were non-nullable. Trying to assign null to them would cause a compile-time error:

Kotlin
// Compile-time error: cannot assign null to non-nullable type
val input: String = null

Declaring Nullable Types #

Let’s see how you can use nullable types when necessary.

The nullable counterpart of some type A is denoted as A?. For example, String? denotes a nullable string and Int? denotes a nullable integer.

If you’re familiar with union types (e.g. from TypeScript), think of these as String? = String | null. In other words, a String? is either a String or null.

Assigning null to a nullable type works as you’d expect:

Kotlin
val input: String? = null

Using Nullable Objects

...