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
- Start with A missing string
- Do this Use a safe call and a default
- Result 0
fun main() {
val text: String? = null
println(text?.length ?: 0)
}
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.
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
fun label(name: String?): String =
name?.trim()?.takeIf { it.isNotEmpty() } ?: "guest"
fun main() {
println(label(" Ada "))
println(label(" "))
println(label(null))
}
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.