Part 03 / Topic 2 of 8
Safe call: ?.
?. calls a method or reads a property only if the value in front of it isn't null. If it
is null, the whole expression evaluates to null immediately — no call happens, and nothing
crashes.
val email: String? = emails[user] // missing key -> null, never an exception
val domain: String? = email?.substringAfter("@") // ?. skips the call entirely when email is null
?. chains exactly the way you'd hope: each link only runs if every link before it was
non-null, so one missing value anywhere in the chain just makes the whole expression null,
instead of crashing partway through.
val length: Int? = nested?.get("asha.rao")?.uppercase()?.length
val missingChain: Int? = nested?.get("not.a.user")?.uppercase()?.length // null, no exception
$ kotlinc 02_safe_call.kt -include-runtime -d 02.jar
$ java -jar 02.jar
asha.rao -> [email protected], domain=example.in
vikram.singh -> [email protected], domain=example.in
deepa.iyer -> email=null, domain=null
chained length = 19
missing chain = null
Full program: examples/02_safe_call.kt.
Done here? The practice set for Part 3 — including the solutions — is on the part page.