tezvyn:

What do the safe call and Elvis operators do in Kotlin?

AI-drafted, machine-checkedSource: kotlinlang.orgbeginner
What do the safe call and Elvis operators do in Kotlin?
WHAT IT TESTS

Kotlin null-safety and default-value fallback.

ANSWER OUTLINE

?. yields null if receiver is null; ?: provides the right operand when left is null; chain as val len = str?.length ?: 0.

RED FLAG

Using !!, verbose if checks, or stating ?.

WHAT THIS TESTS: Your understanding of Kotlin's compile-time null-safety and your ability to handle nullable types idiomatically. The interviewer wants to see that you know how to access members on a nullable receiver without triggering a NullPointerException and how to supply a default value in a single expression rather than resorting to verbose control flow or unsafe assertions.

A GOOD ANSWER COVERS: Four things in order. First, define the safe call operator ?. as an operator that evaluates the property or function call only when the receiver is non-null, otherwise producing null. Second, define the Elvis operator ?: as a binary operator that returns its left operand if that operand is non-null, otherwise returning its right operand. Third, explain that these operators are designed to work together so that ?. can produce a nullable intermediate result and ?: can immediately provide a fallback. Fourth, provide a concise code example such as val length = text?.length ?: 0 where text is a String?, demonstrating that if text is null the expression evaluates to 0 without an NPE.

COMMON WRONG ANSWERS: Three red flags stand out. One is using the not-null assertion !! to force unwrap the nullable, which defeats Kotlin's null-safety and can crash at runtime. Another is writing a multi-line if-else null check when the operators already express the intent more cleanly. A third is incorrectly stating that ?. changes the type from nullable to non-null; in reality ?. still returns a nullable type unless combined with ?: or another null-handling mechanism.

LIKELY FOLLOW-UPS: The interviewer may ask what happens when you chain multiple safe calls together, such as user?.address?.city ?: "Unknown". They might also ask how ?. differs from let, or when you would prefer an explicit if (x != null) block over these operators. Another common follow-up is how these operators interact with platform types coming from Java interop.

ONE CONCRETE EXAMPLE: Imagine a function that formats a user label from a nullable User object. You can write val label = user?.name?.capitalize() ?: "Guest". Here, user?.name returns null if user is null, name?.capitalize() returns null if name is null, and ?: "Guest" substitutes the default string whenever any part of the chain yields null. The result is a non-null String without any branching.

Source: kotlinlang.org

Read the original → kotlinlang.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.