Bird
0
0

Given this Kotlin code, what will result be?

hard📝 Application Q8 of 15
Kotlin - Operators and Expressions

Given this Kotlin code, what will result be?

fun getName(): String? = null
fun getDefaultName(): String = "Guest"
val result = getName() ?: getDefaultName() ?: "Unknown"
A"Guest"
B"Unknown"
Cnull
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Evaluate getName() call

    getName() returns null.
  2. Step 2: Evaluate getDefaultName() call

    getDefaultName() returns "Guest", which is not null.
  3. Step 3: Elvis operator chain result

    Since getDefaultName() is not null, result is "Guest".
  4. Final Answer:

    "Guest" -> Option A
  5. Quick Check:

    Elvis operator returns first non-null in chain [OK]
Quick Trick: Elvis operator calls functions left to right until non-null [OK]
Common Mistakes:
MISTAKES
  • Expecting "Unknown"
  • Ignoring function return values
  • Assuming null is returned

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes