Search⌘ K
AI Features

Dealing with Nulls and Making Asynchronicity Explicit

Explore effective methods for managing null values in Kotlin, including the safe call operator and scoping functions to avoid crashes. Understand how to make asynchronous code explicit by properly naming async functions and using await, ensuring predictable and clear behavior in your applications.

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 half
val stringOrNull: String? = if (Random.nextBoolean())
"String" else null
// Java-way check
if (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, this operator will return its value. Otherwise, it ...