Bird
0
0

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

hard📝 Application Q15 of 15
Kotlin - Variables and Type System
Given the following Kotlin code, what will be the output?
val map = mutableMapOf("a" to 1, "b" to 2)
map["a"] = 3
println(map)

Explain why this works even though map is declared with val.
A{a=3, b=2}
B{a=1, b=2}
CCompilation error: cannot modify val map
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Understand val with mutable collections

    val means the reference to the map cannot change, but the map's content can be modified.
  2. Step 2: Analyze the map update

    Updating key "a" to 3 changes the map content, so printing shows {a=3, b=2}.
  3. Final Answer:

    {a=3, b=2} -> Option A
  4. Quick Check:

    val reference + mutable map = updated map content [OK]
Quick Trick: val fixes reference, mutable map content can change [OK]
Common Mistakes:
MISTAKES
  • Thinking val prevents modifying map content
  • Expecting compilation or runtime errors
  • Confusing immutable reference with immutable object

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes