Null Safety Workbook


Practice problems for Kotlin’s Billion-Dollar Fix. Each takes a minute or two. Write your own answer first, then click Show answer — nothing here is a trick question, just direct practice of the syntax from the lesson.

safe calls and Elvis

1. Safe chain

Given user: User? where a user has an address? with a city, get the city, or null if anything along the way is null.

Show answer Hide answer
user?.address?.city

2. A fallback value

Given name: String?, produce the name or "unknown" when it’s null.

Show answer Hide answer
name ?: "unknown"

3. Elvis with an early return

Inside a function, bind token to request.token, or return null when it’s null.

Show answer Hide answer
val token = request.token ?: return null

4. Length or zero

Given maybe: String?, get its length, or 0 if null, in one expression.

Show answer Hide answer
maybe?.length ?: 0

casts, let, and lateinit

5. Safe cast with a default

Given value: Any, get it as an Int, or 0 if it isn’t one.

Show answer Hide answer
value as? Int ?: 0

6. Run only when present

Given email: String?, call sendWelcome(email) only when it isn’t null.

Show answer Hide answer
email?.let { sendWelcome(it) }

7. Assigned later

Declare a non-null repository: UserRepository you’ll assign in a separate setUp() method, without making it nullable.

Show answer Hide answer
lateinit var repository: UserRepository

fun setUp() {
    repository = UserRepository()
}

collections and Java

8. Drop the nulls

Given names: List<String?>, produce a List<String> with the nulls removed.

Show answer Hide answer
names.filterNotNull()

9. Pin a Java result

A Java method javaApi.getName() returns a platform type. Assign it to a Kotlin val asserting it’s non-null (failing fast if it isn’t).

Show answer Hide answer
val name: String = javaApi.getName()

The explicit non-null type makes Kotlin check at this boundary instead of letting a null slip downstream.

10. The escape hatch

Given maybe: String? that you’re certain is set, get its length with a not-null assertion. What happens if you’re wrong?

Show answer Hide answer
maybe!!.length

If maybe is null, !! throws a NullPointerException on the spot. Reach for it rarely.


Back to the lesson, Kotlin’s Billion-Dollar Fix, or on to the next one: collections.