Nullable Type (?) (Kotlin)

A nullable type is a type marked with a trailing ? (like Int? or String?) that is allowed to hold null. Without the ?, a Kotlin type can never be null.

Kotlin

By default Kotlin types are non-nullable, so String x = null won't compile. Adding ? — String? — opts that variable into possibly being null. This makes nullability part of the type, visible in every signature.

Once a value is nullable, the compiler stops you from calling members on it directly; you must first deal with the null case via ?., ?:, !!, or an explicit null check. After an if (x != null) check, a smart cast lets you use x as non-null inside the block.

Nullable types also interact with platform types from Java: values coming from Java code are 'platform types' that Kotlin treats leniently, so it's good practice to annotate or wrap them to restore null safety.

Syntax

var age: Int? = null
val city: String? = readLine()

Examples

Kotlin

val numbers: List<Int?> = listOf(1, null, 3)
val sum = numbers.filterNotNull().sum()
println(sum)

Output:

4

Learn it in a lesson

See also

Back to the Dictionary