Lesson contents

Kotlin — Null safety with safe calls and Elvis

Combine safe calls and the Elvis operator to normalize a nullable name.

A simple example

Read a nullable value

  1. Start with A missing string
  2. Do this Use a safe call and a default
  3. Result 0
The safe call gives null when the string is missing. The Elvis operator then supplies zero.
Lesson.kt
fun main() {
    val text: String? = null
    println(text?.length ?: 0)
}
Output
0
Advertisements

Choose a label for missing or blank text

The safe call skips trim for a null receiver. takeIf discards an empty result, and the Elvis operator supplies a default for either missing or blank input.

Name with spaces: Ada after trimming. Blank name: guest. Missing name: guest.
Print a usable name badge

A check-in desk trims the name on each registration. A padded name becomes Ada. When the name is blank or missing, print guest so the badge still has a readable label.

Run the example

Kotlin/JVM. Run these commands from the directory containing the example.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar
Lesson.kt
fun label(name: String?): String =
    name?.trim()?.takeIf { it.isNotEmpty() } ?: "guest"

fun main() {
    println(label(" Ada "))
    println(label(" "))
    println(label(null))
}
Output
Ada
guest
guest

The first input becomes Ada. The second becomes empty after trimming, and the third is null. Both select the fallback guest.

Try it yourself

Pass a name containing an internal space.

Check your answer

The internal space remains. For example, Ada Lovelace is returned as written.

Kotlin language documentation

Related tags

  • Kotlin
  • nullable types
  • safe calls
  • Elvis operator