TExcelTAD
Home › Kotlin › Kotlin Null Safety

Kotlin Null Safety

Tony Hoare, who invented the null reference, called it his "billion-dollar mistake": in many languages any object variable may secretly be null, and using it crashes the program with a NullPointerException. Kotlin builds nullability into the type system, so the compiler knows which values can be null and forces you to handle them.

Nullable and non-nullable types

A normal type like String can never hold null. Add a ? to allow it: String?.

kotlin · try it yourself
fun main() {
    var name: String = "Ada"
    name = null
}
File.kt:3:12: error: Null cannot be a value of a non-null type 'String'.
kotlin · try it yourself
fun main() {
    var nickname: String? = "Addy"
    println(nickname)
    nickname = null
    println(nickname)
}
Addy
null

You can't call members directly on a nullable value — the compiler doesn't know whether it's null:

kotlin · try it yourself
fun main() {
    val nickname: String? = "Addy"
    println(nickname.length)
}
File.kt:3:21: error: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type 'String?'.

The tools for nullable values

Operator Name Meaning
a?.b safe call a.b if a isn't null, otherwise null
a ?: b Elvis a if it isn't null, otherwise b
a!! non-null assertion a, or throw NullPointerException if null
if (a != null) null check smart-casts a to non-null inside
a?.let { … } scoped call run the block only when a isn't null
as? safe cast cast, or null if the type doesn't match

Safe calls and Elvis

kotlin · try it yourself
fun main() {
    val names: List<String?> = listOf("Lin", null, "Gabriela")
    for (n in names) {
        val len = n?.length          // Int? - null if n is null
        val safeLen = n?.length ?: 0 // Int  - default 0
        println("$n -> $len / $safeLen")
    }
}
Lin -> 3 / 3
null -> null / 0
Gabriela -> 8 / 8

Safe calls can be chained: user?.address?.city?.uppercase() returns null as soon as any link in the chain is null.

kotlin · try it yourself
data class Address(val city: String?)
data class User(val name: String, val address: Address?)

fun cityOf(u: User?): String = u?.address?.city ?: "unknown"

fun main() {
    println(cityOf(User("Ana", Address("Porto"))))
    println(cityOf(User("Ben", Address(null))))
    println(cityOf(User("Cy", null)))
    println(cityOf(null))
}
Porto
unknown
unknown
unknown

The right side of ?: can also be return or throw, a neat way to exit early:

kotlin
fun shippingLabel(u: User): String {
    val city = u.address?.city ?: return "No address on file"
    return "Ship to $city"
}

Smart casts after null checks

After you check for null, the compiler treats the variable as non-null:

kotlin · try it yourself
fun describe(text: String?) {
    if (text == null) {
        println("Nothing to describe")
        return
    }
    // text is smart-cast to String here
    println("'$text' has ${text.length} characters")
}

fun main() {
    describe("kotlin")
    describe(null)
}
'kotlin' has 6 characters
Nothing to describe

let for nullable values

?.let { … } runs a block only when the value is not null, with the value available as it:

kotlin · try it yourself
fun main() {
    val emails = listOf("a@x.io", null, "c@x.io")
    emails.forEach { email ->
        email?.let { println("Sending to $it") }
    }
    println(emails.filterNotNull())
}
Sending to a@x.io
Sending to c@x.io
[a@x.io, c@x.io]

The !! operator

!! tells the compiler "trust me, it's not null". If you're wrong, you get the very crash null safety tries to prevent:

kotlin · try it yourself
fun main() {
    val input: String? = null
    println(input!!.length)
}
Exception in thread "main" java.lang.NullPointerException

Tip: Treat every !! as a code smell. There's almost always a clearer option: ?: with a default, an early return, requireNotNull(x) { "message" } or restructuring so the value can't be null.

Nulls from Java

Values coming from Java code have platform types (shown as String!): Kotlin doesn't know whether they can be null. Treat them as nullable when in doubt.

Test yourself

What does val x: String = null do?

  1. Creates an empty string
  2. Compile error
  3. Throws at runtime
  4. Creates a nullable String

What is the value of val s: String? = null; s?.length ?: -1?

  1. null
  2. 0
  3. -1
  4. NullPointerException

What happens when you use !! on a null value?

  1. It returns null
  2. It returns a default value
  3. It throws a NullPointerException
  4. Compile error