Nullable Types

After this lesson, you'll be able to recognize and use nullable types, and know how to work with nullables effectively by using Kotlin's special operators to safely access potentially null data.

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:

Press + to interact
// 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:

Press + to interact
val input: String? = null

Using Nullable Objects

...
Access this course and 1400+ top-rated courses and projects.