Bird
0
0

What is the issue with the following Kotlin code?

medium📝 Debug Q6 of 15
Kotlin - Collections Fundamentals
What is the issue with the following Kotlin code?
val numbers = listOf(10, 20, 30)
numbers.add(40)
AThe list must be declared with var instead of val
BThe add() method requires an index parameter
ClistOf() creates an immutable list, so add() is not allowed
DThe listOf() function does not accept integers
Step-by-Step Solution
Solution:
  1. Step 1: Understand listOf()

    listOf() creates an immutable list in Kotlin.
  2. Step 2: Check add() method

    add() is a mutating method and cannot be called on immutable lists.
  3. Step 3: Evaluate other options

    The add() method requires an index parameter is incorrect because add() can be called without index on mutable lists. The list must be declared with var instead of val is irrelevant since val or var does not affect mutability of the list itself. The listOf() function does not accept integers is false; listOf() accepts integers.
  4. Final Answer:

    listOf() creates an immutable list, so add() is not allowed -> Option C
  5. Quick Check:

    Immutable list cannot be modified [OK]
Quick Trick: listOf() returns immutable list; add() only works on mutable lists [OK]
Common Mistakes:
MISTAKES
  • Thinking val vs var affects list mutability
  • Assuming add() always requires index
  • Believing listOf() cannot hold integers

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes