Elvis operator (?:) for default values in Kotlin - Time & Space Complexity
We want to see how using the Elvis operator affects the speed of code when handling values that might be missing.
How does the time to get a value change as the input changes?
Analyze the time complexity of the following code snippet.
fun getLength(text: String?): Int {
return text?.length ?: 0
}
fun processList(list: List): List {
return list.map { getLength(it) }
}
This code gets the length of each string in a list, using 0 if the string is null.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the list with
map. - How many times: Once for every element in the list.
Each item in the list is checked once to get its length or default to zero.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 length checks |
| 100 | 100 length checks |
| 1000 | 1000 length checks |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the list size.
[X] Wrong: "Using the Elvis operator makes the code run faster or slower depending on input size."
[OK] Correct: The Elvis operator just picks a value quickly; it does not add loops or extra work that grows with input size.
Understanding how simple operators like Elvis affect performance helps you write clear and efficient code, a skill valued in real projects and interviews.
"What if we replaced the list.map with a nested loop over a list of lists? How would the time complexity change?"
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
