null has been described as
the billion-dollar mistake.
One of Kotlin’s strongest features is its handling of
It provides both great features for avoiding the use of
null, and for managing
null references in places where they must be used.
null references have proved to be a nightmare to work with.
The "billion-dollar" in the "billion-dollar mistake" refers to a rough estimate
of the amount of time and damage caused by poor handling of
null in computer
The problem is exacerbated by the fact that many languages—like
Java—provide very little help in working safely with
Here’s my favorite example:
Why oh why, in the Year 2020, does the Java compiler still let me do this? It is inexplicable.
And yes, it is fair to say that Java has worked around this, particularly
through the use of language annotations.
But the core language support for safely using
null is missing.
null support in Kotlin is one of the language’s strongest
We’ll return to Kotlin’s
null support multiple times.
But the first place where you see it in use is when declaring variables.
By default variables in Kotlin cannot be assigned a null value.
If you want a nullable type in Kotlin, you can postfix the type name with a question mark:
That said, although Kotlin provides excellent support for safely working with
null, usually your best strategy when programming in Kotlin is to avoid using
null whenever possible.