What if you could replace long null checks with a tiny symbol that saves you time and headaches?
Why Elvis operator (?:) for default values in Kotlin? - Purpose & Use Cases
Imagine you have a list of user names, but some names might be missing or null. You want to show each name, but if a name is missing, you want to show "Guest" instead.
Without a shortcut, you have to write extra checks for every name before showing it.
Checking each name manually is slow and boring. You might forget to check some names, causing errors or crashes. The code becomes long and hard to read, making it easy to make mistakes.
The Elvis operator (?:) lets you quickly say: "If this value is null, use this default instead." It makes your code shorter, cleaner, and safer by handling missing values in one simple step.
val displayName = if (name != null) name else "Guest"
val displayName = name ?: "Guest"You can handle missing or null values effortlessly, making your programs more reliable and easier to read.
When showing user profiles, you can display their name if available, or "Guest" if not, without writing long checks every time.
Manual null checks are slow and error-prone.
The Elvis operator provides a quick default value when something is null.
This makes code cleaner, safer, and easier to understand.
Practice
?: do in Kotlin?Solution
Step 1: Understand the Elvis operator purpose
The Elvis operator?:is used to provide a default value when the left side is null.Step 2: Analyze the behavior
If the left value is not null, it returns that value; otherwise, it returns the right value as a fallback.Final Answer:
Returns the left value if it is not null; otherwise returns the right value -> Option DQuick Check:
Elvis operator = default value if null [OK]
- Thinking it compares two values
- Assuming it throws an error on null
- Confusing it with string conversion
Solution
Step 1: Recall the correct Elvis operator syntax
The Elvis operator is written as?:without any extra characters or spaces.Step 2: Match the syntax with options
val result = value ?: defaultValue uses?:correctly between the variable and the default value.Final Answer:
val result = value ?: defaultValue -> Option CQuick Check:
Correct Elvis syntax = value ?: defaultValue [OK]
- Using single question mark instead of ?:
- Adding extra question marks
- Swapping the order of symbols
val name: String? = null val displayName = name ?: "Guest" println(displayName)
Solution
Step 1: Check the value of
The variablenamenameis explicitly set tonull.Step 2: Apply the Elvis operator
Sincenameis null,displayNamegets the default value "Guest".Final Answer:
Guest -> Option BQuick Check:
null ?: "Guest" = "Guest" [OK]
- Assuming it prints null
- Thinking it prints variable name
- Expecting a compile error
val input: String? = null val output = input ? "Default"
Solution
Step 1: Examine the operator used
The code uses?instead of the Elvis operator?:.Step 2: Understand correct Elvis operator usage
The Elvis operator must be?:to provide a default value when the left side is null.Final Answer:
Incorrect operator used; should be ?: instead of ? -> Option AQuick Check:
Elvis operator must be ?: not ? [OK]
- Using single question mark instead of Elvis operator
- Forgetting the default value after ?:
- Assuming nullable variables cause error here
finalScore?fun calculateScore(score: Int?): Int {
return score ?: 0
}
val userScore: Int? = 5
val finalScore = calculateScore(userScore ?: 10)Solution
Step 1: Evaluate the expression inside the function call
The argument isuserScore ?: 10. SinceuserScoreis 5 (not null), the expression evaluates to 5.Step 2: Call
The function returns the score if not null, so it returns 5.calculateScorewith 5Final Answer:
5 -> Option AQuick Check:
userScore ?: 10 = 5, function returns 5 [OK]
- Thinking userScore ?: 10 returns 10
- Confusing function return with argument default
- Assuming null causes error here
Ready to prove it?
Pass the test and this pattern moves unknown
