Kotlin’s type system is aimed at eliminating the danger of null references from code, also known as the The Billion Dollar Mistake.
One of the most common pitfalls in many programming languages, including Java, is that accessing a member of a null reference will result in a null reference exception. In Java this would be the equivalent of a NullPointerException
or NPE for short.
In Kotlin, the type system distinguishes between references that can hold null
(nullable references) and those that can not (non-null
references). For example, a regular variable of type String can not hold null:
var a: String = "abc"
a = null // compilation error
To allow nulls, we can declare a variable as nullable string, written String?
:
var b: String? = "abc"
b = null // ok
print(b)