androidengineers.Book a session

Null Safety and the Type System

Safe Calls, Elvis, and let

article15 minEasy

Compose nullable operations deliberately

A safe call ?. runs an operation only for a non-null receiver. Elvis ?: supplies an alternative when the expression to its left is null. let transforms or works with a value named it, or an explicit lambda parameter.

fun parseBudget(input: String?): Int? =
    input?.trim()?.toIntOrNull()?.takeIf { it > 0 }

fun main() {
    val budget = parseBudget(" 50 ") ?: 25
    println(budget)
    parseBudget("10")?.let { minutes ->
        println("Accepted $minutes minutes")
    }
}

Safe calls propagate absence through the pipeline. takeIf adds domain validation after parsing. The fallback of 25 is an intentional policy; if invalid input must be shown to the user, returning a default would hide an error instead.

Elvis applies to the entire nullable expression, not just the initial receiver. A transformation returning null can trigger the fallback even when the input was non-null.

Exercise

Write a function that returns a trimmed nonblank email string or null without attempting full email validation. Test null, whitespace, and a populated value.

Check: explain when a fallback is appropriate and when the caller needs an explicit validation error.

Reference: Scope functions

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Safe Calls, Elvis, and let | Kotlin Core Programming | Android Engineers