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 IT TESTS: Whether you understand Kotlin null-safety and can combine safe calls with default values instead of branching. ANSWER OUTLINE: First, state that ?. evaluates a member only if the receiver is non-null, yielding null otherwise; second, state that ?: returns its right operand when the left side is null; third, show chaining as val displayName = user?.name ?: "Anonymous". RED FLAG: Using !!, verbose if-null checks, or claiming ?. removes nullability from the type.
Read the original → kotlinlang.org
- #kotlin
- #null-safety
- #operators
- #android
- #interview
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.