Null safety

Null safety

Sir Tony Hoare IMG 5125

I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.

 — Tony Hoare (QCon London 2009)

Null safety is enforced by having two type universes: nullable (with nullable types T?) and non-nullable (with non-nullable types T).

cannot assign null

To allow null values, you have to declare a variable with a ? sign right after the variable type.

1val name: String? = null

Safe call operator

The safe call operator ?. returns null instead of throwing an NPE when the object is null.

unsafe call
1    fun convert(name: String?): String? {
2        return name?.uppercase()
3    }

Not-null assertion operator

On the contrary, the not-null assertion operator !! treats the variable as non-nullable and should be used when you’re certain the variable won’t be null, even if the compiler can’t verify it.

1val name: String? = "Isagi"
2val len = name!!.length

Elvis operator

The Elvis operator ?: returns the expression on the left if it’s not null; otherwise, it returns the expression on the right.

1val symbolsByCodes = mapOf("EUR" to "€", "USD" to "$", "£" to "GBP")
2val symbol = symbolsByCodes["JPY"] ?: "Unknown currency code"

Other tools

Refer to the documentation.