Skip to content
tezvyn:

Purpose of Kotlin's safe call (`?.`) and Elvis (`?:`) operators?

Source: kotlinlang.orgEasyHow cards are made

Purpose of Kotlin's safe call (`?.`) and Elvis (`?:`) operators?

This tests your grasp of Kotlin's null safety philosophy. A good answer defines the safe call (?.) for conditional access and the Elvis operator (?:) for default values, then combines them. A red flag is using verbose if/else checks for simple cases.

What's really being asked

This question tests your understanding of Kotlin's core null safety philosophy. For a senior engineer, it's not about knowing the syntax, but about demonstrating a commitment to writing idiomatic, compile-time-safe code. The interviewer wants to see that you can avoid NullPointerExceptions by default, using the language's features to write concise and expressive code for handling nullable data.

The full answer

First, define the Safe Call operator (?.). It's for conditional execution. It accesses a property or calls a method only if the receiver is not null. If the receiver is null, the entire expression short-circuits and evaluates to null, preventing an NPE.

Second, define the Elvis operator (?:). It's for providing a default value. It evaluates the expression on its left; if that expression is not null, it returns it. If the expression is null, it evaluates and returns the expression on its right. This is more powerful than a simple default, as the right-hand side can be any expression, including a return or throw.

Third, explain how they chain together to form a single, readable expression for safely traversing an object graph and providing a fallback. This pattern is fundamental to idiomatic Kotlin.

The mistakes people make

Reaching for the non-null assertion operator (!!). This is a major red flag. It manually overrides the compiler's safety checks and re-introduces the risk of runtime NPEs. A senior candidate should know to avoid !! unless there is an external guarantee of non-nullness that the compiler cannot infer.

Writing a verbose if (x != null) { ... } else { ... } block. While functionally correct, it's not idiomatic for this simple case and suggests the candidate is still thinking in Java rather than Kotlin. The goal is concise, expression-based code.

Confusing the Elvis operator with a ternary operator from other languages. The Elvis operator specifically acts on a null value, not a general boolean condition.

What usually comes next

"When would you use the !! operator?" (Answer: Sparingly. After an explicit if check that smart-casting can't resolve, or when interoperating with a Java library where you have an external guarantee of non-nullness.)

"How does this compare to Java's Optional?" (Answer: Kotlin's nullable types are a more lightweight, language-level feature. Optional is a library class that creates a wrapper object, which has a slight performance and ergonomic overhead compared to the native ? syntax.)

"How does let fit in? When would you use user?.let { ... }?" (Answer: let is a scope function for executing a block of code on a non-null value. It's ideal for performing multiple operations or transformations, whereas ?. is for simple property access or method call chains.)

A concrete example

data class User(val name: String?)

fun getUserNameLength(user: User?): Int { // Safely access user, then name, then get length. // If user or name is null, the Elvis operator provides a default of 0. return user?.name?.length ?: 0 }

// Example usage: val userWithText = User("Alice") // user.name.length is 5 val userWithNullName = User(null) // user.name is null val nullUser: User? = null // user is null

val length1 = getUserNameLength(userWithText) // returns 5 val length2 = getUserNameLength(userWithNullName) // returns 0 val length3 = getUserNameLength(nullUser) // returns 0

Interview question

Given a nullable `user: User?`, how do you safely get its name's length, returning 0 if either `user` or its `name` property is null?

  • a.user?.name?.length
  • b.user!!.name!!.length
  • c.if (user != null && user.name != null) user.name.length else 0
  • d.user?.name?.length ?: 0Correct
Why?

The safe call `?.` accesses properties only if the object is not null, and the Elvis operator `?:` provides the default value `0` if the preceding expression is null. The `if/else` block is verbose and not idiomatic Kotlin.

Just read this? Test yourself on what you have been reading.

Read the original → kotlinlang.org

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on kotlin — each one lists the topics its interview covers.

See open roles