Dealing with Nulls and Making Asynchronicity Explicit
Learn how to efficiently handle nulls in Kotlin code and how can we make asynchronicity explicit.
We'll cover the following...
Dealing with nulls
Nulls are unavoidable, especially if we work with Java libraries or get data from a database. We’ve already discussed that there are different ways to check whether a variable contains null
in Kotlin; for example:
// Will return "String" half of the time and null the other halfval stringOrNull: String? = if (Random.nextBoolean())"String" else null// Java-way checkif (stringOrNull != null) {println(stringOrNull.length)}
Prints the length of stringOrNull if it's not null
We could rewrite this code using the Elvis operator (?:
):
val alwaysLength = stringOrNull?.length ?: 0
If the length is not null
, ...