Bird
0
0

What will happen when the following Kotlin code is executed?

medium📝 Predict Output Q5 of 15
Kotlin - Collections Fundamentals
What will happen when the following Kotlin code is executed?
val items = listOf("a", "b", "c")
items.add("d")
ACompilation error because add() is not available on immutable lists
BThe element "d" is added successfully to the list
CRuntime exception due to unsupported operation
DThe list is converted to mutable automatically and "d" is added
Step-by-Step Solution
Solution:
  1. Step 1: Understand listOf() returns immutable list

    listOf() creates an immutable list without add() method.
  2. Step 2: Check method availability

    add() is not defined for immutable lists, so code won't compile.
  3. Final Answer:

    Compilation error because add() is not available on immutable lists -> Option A
  4. Quick Check:

    Immutable lists lack add() method [OK]
Quick Trick: Immutable lists do not have add() method [OK]
Common Mistakes:
MISTAKES
  • Expecting add() to work on immutable lists
  • Assuming runtime exception instead of compile error
  • Believing list converts to mutable automatically

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes