KOTLIN / CHAPTER 04

Null safety and validation

Intermediate

Make absent values explicit before using them.

By the end of this chapter

  • Read nullable type syntax
  • Combine safe calls with Elvis fallback
  • Avoid unjustified non-null assertions

The idea

A nullable type such as String? can hold either a string or null. Kotlin requires code to account for that absence before using members that need a real string. A safe call, written ?., runs the member access only when the receiver is present and otherwise returns null. The Elvis operator ?: supplies an alternative when its left side is null.

Do not treat an empty string as equivalent to null unless the requirement says so. The non-null assertion !! removes a compiler check by requesting a runtime failure if the value is absent. Prefer validation that narrows the type, safe calls, or a meaningful early return when absence is an expected part of the input.

Kotlin example
fun displayLength(name: String?): Int = name?.trim()?.length ?: 0
fun main() {
  println(displayLength("  Kai  "))
  println(displayLength(null))
}
Result
3
0

The present string is trimmed before its length is read. Null passes through the safe-call chain and selects the fallback zero.

Try it yourself

Return a trimmed nonempty display name or Guest for null and whitespace-only input.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What is printed?
val name: String? = ""
println(name?.length ?: 9)