Android ● ○ ○ Kotlin 2.0

Kodebits Day 7: Null-safe Length

Apr 17 2026
Use Kotlin null safety and the Elvis operator in one small function.

What is the output?

fun lenOrZero(s: String?): Int {
  return s?.length ?: 0
}
fun main() {
  println(lenOrZero("kotlin"))
  println(lenOrZero(null))
}


Try it in the online Kotlin Playground →

[spoiler title="Solution"]

Answer:

6
0

Explanation:

The safe call returns null for a null string, then ?: supplies 0.

[/spoiler]


Further Reading