Bird
0
0

What will be the output of this Kotlin code?

medium📝 Predict Output Q4 of 15
Kotlin - Collections Fundamentals
What will be the output of this Kotlin code?
val list: List = listOf(1, 2, 3)
// list.add(4) // Uncommenting this line
println(list)
A[1, 2, 3]
BCompilation error due to add() on immutable List
C[1, 2, 3, 4]
DRuntime exception when calling add()
Step-by-Step Solution
Solution:
  1. Step 1: Understand List interface mutability

    List is immutable and does not have add() method, so calling add() causes a compile error.
  2. Step 2: Analyze code behavior

    Uncommenting list.add(4) will cause compilation failure, so no output is produced.
  3. Final Answer:

    Compilation error due to add() on immutable List -> Option B
  4. Quick Check:

    Immutable List disallows add() [OK]
Quick Trick: Immutable List has no add() method; causes compile error [OK]
Common Mistakes:
MISTAKES
  • Expecting runtime error instead of compile error
  • Assuming add() works on List
  • Confusing List with MutableList

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes