Nullability
The dreaded NullPointerException
has been the bane of many Java developers. And Java actually handles null
values relatively well, compared to languages like C/C++, where null pointers can have more damaging effects.
The designers of Kotlin elected to try to do something about it, by adding nullability to types, so that developers can be more aware of where null
is (and is not) allowed, through compile-time type checking. It is not a perfect solution, but it does go a long way towards eliminating NullPointerException
and related bugs.
Introducing Nullable Types
So far in this book, we have used types like Int
, Boolean
, String
, and Axolotl
. These types are normal Kotlin types… and they do not allow null
.
So, if you try this:
val notGonnaHappen : String = null
…you get:
error: null can not be a value of a non-null type String
val notGonnaHappen : String = null
^
This is not merely a limitation of assignments. Any place where the type does not allow null
, you cannot use a null
value. So, this too fails with a compile error:
fun gotNoTimeForNull(parameter: String) {
println(parameter)
}
fun main() {
gotNoTimeForNull(null)
}
To say that null
is a valid value, you append ?
to the type, giving you types like Int?
, Boolean?
, String?
, and Axolotl?
. So, this works:
val notGonnaHappen : String? = null
fun gotNoTimeForNull(parameter: String?) {
println(parameter)
}
fun main() {
gotNoTimeForNull(notGonnaHappen)
}
You might be worried about that println(parameter)
statement. If parameter
can be null
, might that crash with a NullPointerException
? The answer is no, that statement is safe, yielding:
null
However, in general, the concern is valid: you need to make sure that what you pass a nullable type to can support null
. However, that is the big advantage of this being part of Kotlin’s type system: most of the time, if null
is not allowed, a nullable type is not allowed, and you fail with some form of compilation error. If Kotlin code allows you to pass a null
— as println()
does — then it is up to that code to handle null
gracefully.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.