Bird
0
0

What will be the output of this Kotlin code?

medium📝 Predict Output Q13 of 15
Kotlin - Collections Fundamentals
What will be the output of this Kotlin code?
val numbers = listOf(1, 2, 3)
numbers.add(4)
AList will contain [1, 2, 3, 4]
BCompilation error: Unresolved reference 'add'
CRuntime error: UnsupportedOperationException
DList remains [1, 2, 3] without error
Step-by-Step Solution
Solution:
  1. Step 1: Recognize listOf creates immutable list

    The listOf() function returns an immutable list that does not support modification methods like add().
  2. Step 2: Understand behavior of calling add() on immutable list

    Calling add() on a List<T> causes a compilation error because List<T> has no add() method: Unresolved reference 'add'.
  3. Final Answer:

    Compilation error: Unresolved reference 'add' -> Option B
  4. Quick Check:

    Immutable list + add() = compile error [OK]
Quick Trick: Immutable lists have no add() method: compile error [OK]
Common Mistakes:
MISTAKES
  • Expecting runtime error instead of compile-time error
  • Assuming add() works on immutable lists
  • Thinking list remains unchanged silently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes