Bird
0
0

You want to create a list of strings that you can add items to later. Which Kotlin code correctly creates this list and adds "orange" to it?

hard📝 Application Q15 of 15
Kotlin - Collections Fundamentals
You want to create a list of strings that you can add items to later. Which Kotlin code correctly creates this list and adds "orange" to it?
Aval fruits = mutableListOf("apple", "banana") fruits = fruits + "orange"
Bval fruits = listOf("apple", "banana") fruits.add("orange")
Cval fruits = listOf("apple", "banana") fruits += "orange"
Dval fruits = mutableListOf("apple", "banana") fruits.add("orange")
Step-by-Step Solution
Solution:
  1. Step 1: Choose a mutable list

    To add items later, the list must be mutable, so use mutableListOf.
  2. Step 2: Use add() method correctly

    Calling add("orange") on a mutable list adds the item successfully.
  3. Step 3: Check other options

    val fruits = listOf("apple", "banana") fruits.add("orange") tries to add to immutable list (error). val fruits = listOf("apple", "banana") fruits += "orange" uses += on immutable list (creates new list but does not modify original). val fruits = mutableListOf("apple", "banana") fruits = fruits + "orange" tries to reassign val which is not allowed.
  4. Final Answer:

    val fruits = mutableListOf("apple", "banana") fruits.add("orange") -> Option D
  5. Quick Check:

    Mutable list + add() = correct way [OK]
Quick Trick: Use mutableListOf and add() to change list after creation [OK]
Common Mistakes:
MISTAKES
  • Adding to immutable list
  • Trying to reassign val variable
  • Using += on immutable list expecting mutation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes