Bird
0
0

You need a Kotlin function that returns an immutable list of the first five even numbers. Which function implementation ensures the returned list cannot be modified?

hard📝 Application Q8 of 15
Kotlin - Variables and Type System
You need a Kotlin function that returns an immutable list of the first five even numbers. Which function implementation ensures the returned list cannot be modified?
Afun getEvens(): List<Int> = mutableListOf(2, 4, 6, 8, 10)
Bfun getEvens(): MutableList<Int> = mutableListOf(2, 4, 6, 8, 10)
Cfun getEvens(): ArrayList<Int> = arrayListOf(2, 4, 6, 8, 10)
Dfun getEvens(): List<Int> = listOf(2, 4, 6, 8, 10)
Step-by-Step Solution
Solution:
  1. Step 1: Understand list types

    List is immutable, MutableList is mutable.
  2. Step 2: Analyze options

    fun getEvens(): List = listOf(2, 4, 6, 8, 10) returns an immutable List using listOf.
  3. Step 3: Identify mutable returns

    Options B, C, and D return mutable lists or mutable types.
  4. Final Answer:

    fun getEvens(): List<Int> = listOf(2, 4, 6, 8, 10) -> Option D
  5. Quick Check:

    Use listOf for immutable lists [OK]
Quick Trick: Use listOf() for immutable lists [OK]
Common Mistakes:
MISTAKES
  • Returning mutableListOf() when immutability is required
  • Confusing List and MutableList types
  • Assuming ArrayList is immutable

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes