Bird
Raised Fist0
Kotlinprogramming~10 mins

Elvis operator deep usage in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Elvis operator deep usage
Evaluate expression on left
↓
Is it null?
No→Use left value
Yes↓
Evaluate right expression
↓
Use right value
The Elvis operator checks if the left expression is null; if not, it uses it, otherwise it uses the right expression.
Execution Sample
Kotlin
val name: String? = null
val displayName = name ?: "Guest"
println(displayName)
Assigns 'Guest' if name is null, then prints displayName.
Execution Table
StepExpressionLeft ValueIs Left Null?Right ExpressionResult UsedOutput
1name ?: "Guest"nullYes"Guest""Guest""Guest"
2println(displayName)"Guest"---Guest
💡 Execution ends after printing the displayName value.
Variable Tracker
VariableStartAfter ElvisFinal
namenullnullnull
displayNameuninitialized"Guest""Guest"
Key Moments - 3 Insights
Why does the Elvis operator choose the right side when the left is null?
Because the Elvis operator returns the left value only if it is not null; otherwise, it evaluates and returns the right expression, as shown in execution_table step 1.
What happens if the left side is not null?
The Elvis operator uses the left value directly without evaluating the right side, saving computation and preserving the left value.
Can the right side be any expression?
Yes, the right side can be any expression, including function calls or complex logic, which will only run if the left side is null.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result used at step 1?
Anull
B"Guest"
Cname
DdisplayName
💡 Hint
Check the 'Result Used' column in execution_table row 1.
At which step does the Elvis operator decide to use the right expression?
AStep 1
BStep 2
CNo step, it never uses right expression
DBefore step 1
💡 Hint
Look at the 'Is Left Null?' column in execution_table row 1.
If 'name' was "Alice" instead of null, what would 'displayName' be after Elvis operator?
A"Guest"
Bnull
C"Alice"
DUninitialized
💡 Hint
Refer to the variable_tracker and how Elvis operator uses left value if not null.
Concept Snapshot
Elvis operator syntax: val result = expr1 ?: expr2
Returns expr1 if not null; otherwise expr2.
Right side evaluated only if left is null.
Useful for default values and null safety.
Can chain multiple Elvis operators for fallback.
Full Transcript
The Elvis operator in Kotlin checks if the left expression is null. If it is not null, it uses that value. If it is null, it evaluates and uses the right expression instead. For example, if a variable 'name' is null, using 'name ?: "Guest"' will result in "Guest". This operator helps provide default values when dealing with nullable variables. The right side expression is only evaluated if the left side is null, which can save unnecessary computation. This behavior is shown step-by-step in the execution table and variable tracker. Understanding when the right side runs and how the operator chooses values is key to using it effectively.

Practice

(1/5)
1.

What does the Elvis operator ?: do in Kotlin?

easy
A. Checks if two values are equal.
B. Returns the left value if it is not null; otherwise returns the right value.
C. Converts a value to a nullable type.
D. Throws an exception if the left value is null.

Solution

  1. Step 1: Understand the Elvis operator purpose

    The Elvis operator ?: is used to provide a default value when the left side is null.
  2. Step 2: Analyze the behavior

    If the left value is not null, it returns that value; otherwise, it returns the right value.
  3. Final Answer:

    Returns the left value if it is not null; otherwise returns the right value. -> Option B
  4. Quick Check:

    Elvis operator returns left if not null else right [OK]
Hint: Elvis operator picks left if not null, else right [OK]
Common Mistakes:
  • Thinking it compares two values
  • Assuming it throws exceptions
  • Confusing it with null checks
2.

Which of the following is the correct syntax to use the Elvis operator in Kotlin?

val result = value1 ??: value2
easy
A. val result = value1 ?: value2
B. val result = value1 ? value2
C. val result = value1 :: value2
D. val result = value1 ?:: value2

Solution

  1. Step 1: Identify the correct Elvis operator syntax

    The Elvis operator in Kotlin is written as ?: without spaces.
  2. Step 2: Match the syntax with options

    val result = value1 ?: value2 uses ?: correctly, while others use invalid or incorrect symbols.
  3. Final Answer:

    val result = value1 ?: value2 -> Option A
  4. Quick Check:

    Elvis operator syntax is ?: [OK]
Hint: Elvis operator is always ?: with no spaces [OK]
Common Mistakes:
  • Using single question mark ? instead of ?:
  • Using double colon :: by mistake
  • Adding extra colons or spaces
3.

What is the output of the following Kotlin code?

val a: String? = null
val b: String? = "Hello"
val c: String? = null

val result = a ?: b ?: c ?: "Default"
println(result)
medium
A. Hello
B. null
C. Default
D. Compilation error

Solution

  1. Step 1: Evaluate the chained Elvis operators

    Variable a is null, so Elvis operator moves to b. b is "Hello", which is not null.
  2. Step 2: Determine the final value

    Since b is not null, result is assigned "Hello" and the rest is ignored.
  3. Final Answer:

    Hello -> Option A
  4. Quick Check:

    Chained Elvis picks first non-null: Hello [OK]
Hint: Chained Elvis returns first non-null value [OK]
Common Mistakes:
  • Assuming it returns null if first is null
  • Ignoring chaining and picking last value
  • Thinking it causes a compile error
4.

Identify the error in this Kotlin code snippet using the Elvis operator:

val x: String? = null
val y: String = x ?: null
medium
A. Elvis operator cannot be used with nullable types
B. No error, code is correct
C. Variable x should not be nullable
D. Cannot assign null to non-nullable type String

Solution

  1. Step 1: Analyze variable types and assignment

    Variable y is declared as non-nullable String, but x ?: null can be null.
  2. Step 2: Understand Kotlin's null safety rules

    Assigning null to a non-nullable type causes a compilation error.
  3. Final Answer:

    Cannot assign null to non-nullable type String -> Option D
  4. Quick Check:

    Non-nullable cannot hold null [OK]
Hint: Non-nullable vars cannot be assigned null [OK]
Common Mistakes:
  • Thinking Elvis operator changes nullability
  • Assuming nullable can be assigned to non-nullable
  • Ignoring Kotlin's strict null safety
5.

Given the following Kotlin code, what will be the output?

fun getName(user: Map): String {
    return user["firstName"] ?: user["nickname"] ?: user["lastName"] ?: "Anonymous"
}

val user1 = mapOf("firstName" to null, "nickname" to null, "lastName" to "Smith")
println(getName(user1))
hard
A. Anonymous
B. Compilation error
C. Smith
D. null

Solution

  1. Step 1: Evaluate the map values in order

    firstName and nickname are null, so Elvis operator moves to lastName, which is "Smith".
  2. Step 2: Determine the returned value

    Since lastName is not null, the function returns "Smith".
  3. Final Answer:

    Smith -> Option C
  4. Quick Check:

    Elvis chain returns first non-null: Smith [OK]
Hint: Elvis chains pick first non-null map value [OK]
Common Mistakes:
  • Assuming it returns Anonymous despite lastName present
  • Confusing null with string "null"
  • Thinking map access causes error
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard