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.
We'll cover the following...
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:
// Compile-time error: cannot assign null to non-nullable typeval 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, aString?
is either aString
ornull
.
Assigning null
to a nullable type works as you’d expect:
val input: String? = null