Dealing with nulls
Handling nulls is a critical aspect of Kotlin programming, especially when interfacing with Java libraries or databases. Kotlin provides several tools to deal with nullability in a safe and expressive way.
Kotlin supports traditional null checks similar to Java:
val stringOrNull: String? = if (Random.nextBoolean()) "String" else null
if (stringOrNull != null) {
println(stringOrNull.length)
}
This approach is straightforward but can lead to verbose code, especially with nested null checks.
The Elvis operator offers a concise way to handle null values by providing a default value:
val alwaysLength = stringOrNull?.length ?: 0
If stringOrNull
is not null, alwaysLength
will be its length; otherwise, it defaults to 0.
For nested objects with nullable properties, chaining null-safe calls prevents receiving a NullPointerException
:
data class Response(val profile: UserProfile?)
data class UserProfile(val firstName: String...