Bird
0
0

What does the Kotlin expression map[key] ?: "default" do?

easy📝 Conceptual Q11 of 15
Kotlin - Collections Fundamentals

What does the Kotlin expression map[key] ?: "default" do?

ARemoves the <code>key</code> from the map if it exists.
BReturns the value for <code>key</code> if it exists, otherwise returns "default".
CThrows an error if <code>key</code> is not in the map.
DAlways returns "default" regardless of <code>key</code>.
Step-by-Step Solution
Solution:
  1. Step 1: Understand map access with []

    Accessing map[key] returns the value if key exists, or null if it doesn't.
  2. Step 2: Use the Elvis operator ?: for fallback

    The expression ?: "default" means if the left side is null, return "default" instead.
  3. Final Answer:

    Returns the value for key if it exists, otherwise returns "default". -> Option B
  4. Quick Check:

    map[key] ?: default = safe access with fallback [OK]
Quick Trick: Use ?: to provide a default when key might be missing [OK]
Common Mistakes:
MISTAKES
  • Thinking it throws an error if key is missing
  • Assuming it always returns default
  • Confusing with removing keys

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes