Nullable types
Kotlin's type system is advanced enough that it can track the difference between nullable types and non-nullable types. When we define a variable in Kotlin, as we have been doing so far, we cannot assign a null to it. This code, for instance, would not compile:
val name: String = null // does not compile
Assigning null to a var
will not compile either:
var name: String = "harry" name = null // does not compile
To inform the Kotlin compiler that we will allow a variable to contain a null, we must suffix the type with a ?
:
val name: String? = null var name: String? = "harry" name = null
Both the preceding snippets will now compile.
Similarly, we can return nullable and non-nullable types from a function, use them as function parameters, and so on:
fun name1(): String = ... fun name2(): String? = ...
The name1
function cannot return a null reference. The name2
function may or may not. If we were...