Bird
0
0

You want to create a list of user names that should never change after creation. Which Kotlin declaration is best and why?

hard📝 Application Q15 of 15
Kotlin - Variables and Type System
You want to create a list of user names that should never change after creation. Which Kotlin declaration is best and why?
val users = listOf("Anna", "Bob", "Cara")
AUse <code>val</code> with <code>listOf</code> because it creates an immutable list and reference.
BUse <code>val</code> with <code>mutableListOf</code> to allow adding users later.
CUse <code>var</code> with <code>listOf</code> because the list can be changed later.
DUse <code>var</code> with <code>mutableListOf</code> to change the list and reference.
Step-by-Step Solution
Solution:
  1. Step 1: Understand immutability of variable and list

    val means the reference cannot change, and listOf creates an immutable list that cannot be modified.
  2. Step 2: Compare options

    Use val with listOf because it creates an immutable list and reference. uses val and listOf, ensuring both the reference and list contents cannot change, which matches the requirement.
  3. Final Answer:

    Use val with listOf because it creates an immutable list and reference. -> Option A
  4. Quick Check:

    val + listOf = fully immutable list [OK]
Quick Trick: val + listOf = fixed list and reference [OK]
Common Mistakes:
MISTAKES
  • Using var with mutableListOf when immutability is needed
  • Confusing mutableListOf with listOf
  • Thinking val allows list content changes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes