0
0
Kotlinprogramming~10 mins

Elvis operator (?:) for default values in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Elvis operator (?:) for default values
Evaluate expression on left
Is it null?
NoUse left value
Yes
Use right default value
The Elvis operator checks if the left expression is null; if not, it uses that value, otherwise it uses the right default value.
Execution Sample
Kotlin
val name: String? = null
val displayName = name ?: "Guest"
println(displayName)
This code assigns a default value "Guest" if name is null, then prints the result.
Execution Table
StepExpressionEvaluationResultAction
1namenullnullCheck if null
2name ?: "Guest"null ?: "Guest""Guest"Use right default value
3println(displayName)"Guest"Output: GuestPrint the result
💡 Execution ends after printing the default value because name was null
Variable Tracker
VariableStartAfter Elvis operatorFinal
namenullnullnull
displayNameuninitialized"Guest""Guest"
Key Moments - 2 Insights
Why does displayName become "Guest" when name is null?
Because the Elvis operator ?: checks if name is null (row 1), and since it is, it uses the right side "Guest" as the default value (row 2).
What happens if name is not null?
If name is not null, the Elvis operator returns the left value directly, skipping the default (not shown here but implied by the flow).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table at step 2, what value does the Elvis operator produce?
A"Guest"
Bnull
Cname
DError
💡 Hint
Check the 'Result' column in step 2 of the execution_table
At which step does the program print the output?
AStep 1
BStep 2
CStep 3
DNo print step
💡 Hint
Look for println in the 'Expression' column in execution_table
If name was "Alice", what would displayName be after the Elvis operator?
A"Guest"
B"Alice"
Cnull
DError
💡 Hint
Recall Elvis operator returns left value if not null (concept_flow)
Concept Snapshot
Elvis operator ?: returns left value if not null,
otherwise returns right default value.
Syntax: val result = expr ?: default
Useful for providing fallback values
Avoids explicit null checks.
Full Transcript
The Elvis operator ?: in Kotlin helps assign default values when a variable might be null. It first checks the left expression; if it is not null, it uses that value. If it is null, it uses the right side as a default. In the example, name is null, so displayName becomes "Guest". The program then prints "Guest". If name had a value like "Alice", displayName would be "Alice". This operator simplifies code by avoiding manual null checks.