Bird
0
0

Find the error in this Kotlin code:

medium📝 Debug Q7 of 15
Kotlin - Collections Fundamentals
Find the error in this Kotlin code:
val map = mapOf("a" to 1)
val value = map.getValue("b") ?: 0
println(value)
AThrows exception because getValue throws if key missing
Bvalue will be 0
Cvalue will be null
DCompilation error due to ?: usage
Step-by-Step Solution
Solution:
  1. Step 1: Understand getValue behavior

    getValue(key) throws NoSuchElementException if the key is not present in the map.
  2. Step 2: Analyze ?: operator effect

    The Elvis operator ?: is not reached because exception is thrown before it can be applied.
  3. Final Answer:

    Throws exception because getValue throws if key missing -> Option A
  4. Quick Check:

    getValue throws on missing key, ?: won't catch it [OK]
Quick Trick: Use map[key] ?: default instead of getValue for safe access [OK]
Common Mistakes:
MISTAKES
  • Expecting getValue to return null
  • Assuming ?: handles exceptions
  • Confusing getValue with get()

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes