Bird
0
0

What will be the output of the following Kotlin code?

medium📝 Predict Output Q13 of 15
Kotlin - Variables and Type System
What will be the output of the following Kotlin code?
val list = mutableListOf(1, 2, 3)
list.add(4)
println(list)
ARuntime error
B[1, 2, 3]
CCompilation error
D[1, 2, 3, 4]
Step-by-Step Solution
Solution:
  1. Step 1: Understand val with mutable objects

    val means the reference to the list cannot change, but the list itself can be modified.
  2. Step 2: Analyze code behavior

    Adding 4 to the mutable list changes its content, so printing shows [1, 2, 3, 4].
  3. Final Answer:

    [1, 2, 3, 4] -> Option D
  4. Quick Check:

    val reference + mutable object = modified list [OK]
Quick Trick: val fixes reference, not object content if mutable [OK]
Common Mistakes:
MISTAKES
  • Thinking val prevents modifying the list 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