Nullable Types and Generics
Types that you use in generics can be nullable:
val listOfNullables : MutableList<String?> = mutableListOf()
listOfNullables.add("this is not null")
listOfNullables.add(null)
println(listOfNullables)
Here, listOfNullables
is a MutableList
that can hold String?
instead of just String
. So, we can put both String
objects and null
into the list.
So, we can create a list that can contain null. What if we want the list itself to possibly be null
? In that case, the ?
goes after the generic type:
val nullableList : MutableList<String>? = mutableListOf()
nullableList?.add("this is not null")
nullableList?.add("this is also not null")
println(nullableList)
Here, nullableList
can either be a MutableList
or null
. If it is a MutableList
, though, that list can only hold String
objects.
If we want, we can combine the two:
val nullableListOfNullables : MutableList<String?>? = mutableListOf()
nullableListOfNullables?.add("this is not null")
nullableListOfNullables?.add(null)
println(nullableListOfNullables)
So now not only can nullableListOfNullables
itself be null
, but if it is an actual MutableList
, the list can hold null
values, in addition to String
objects.
And if you find all of this confusing… well, perhaps that is another reason why ?
was chosen as the symbol to use for nullability.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.