Part 03 / Topic 4 of 8
let with the null-safe call
let is a scope function: it takes the value in front of it, hands it to the block as
it (or a name you choose), and returns whatever the block returns. Combined with ?., the
block only ever runs when there's a real, non-null value to hand it — which makes ?.let { }
the idiomatic way to say "if this is present, do something with it."
val email: String? = emails["asha.rao"]
email?.let { address -> sendWelcomeEmail(address) } // runs: asha.rao has an email
val missing: String? = emails["deepa.iyer"]
missing?.let { address -> sendWelcomeEmail(address) } // never runs: deepa.iyer has none
Inside the block, the value is already smart-cast to its non-null type, so address above is a
plain String, not String?. Chain an Elvis on the end and ?.let { } ?: ... reads exactly
like an if/else, as a single expression instead of a statement:
val label = email?.let { "registered: $it" } ?: "not registered"
$ kotlinc 04_let.kt -include-runtime -d 04.jar
$ java -jar 04.jar
sending welcome email to [email protected]
done trying deepa.iyer
registered: [email protected]
not registered
length inside let: 19
🔍 Going deeper:
letis one of several scope functions (run,with,apply,also); Stage 2, Part 10 ("Functional Kotlin") covers the full set and when to reach for which one. For null safety specifically,?.let { }is the one worth knowing by Part 3.
Full program: examples/04_let.kt.
Done here? The practice set for Part 3 — including the solutions — is on the part page.