Kotlin Kotlin Collections 1 — Questions and Answers
Question 1: Which function creates an immutable list in Kotlin?
- mutableListOf()
- arrayListOf()
- listOf() (Correct answer)
- linkedListOf()
Correct answer: listOf()
`listOf()` creates a read-only list in Kotlin that cannot be modified after creation.
Question 2: What does the `map` function do on a Kotlin collection?
- Filters elements based on a condition
- Transforms each element using a given function and returns a new list (Correct answer)
- Groups elements by a key
- Reduces the collection to a single value
Correct answer: Transforms each element using a given function and returns a new list
`map` applies a transformation function to each element of a collection and returns a new list with the transformed values.
Question 3: Which Kotlin collection function returns elements that satisfy a given predicate?
- map
- reduce
- filter (Correct answer)
- groupBy
Correct answer: filter
`filter` returns a new list containing only elements for which the predicate function returns true.
Question 4: What is the difference between `List` and `MutableList` in Kotlin?
- List allows nulls; MutableList does not
- List is read-only; MutableList supports add/remove operations (Correct answer)
- MutableList is faster than List
- There is no difference
Correct answer: List is read-only; MutableList supports add/remove operations
`List` is a read-only interface in Kotlin, while `MutableList` extends it with mutation operations like `add()` and `remove()`.
Question 5: Which function combines all elements of a collection into a single result?
- map
- collect
- fold (Correct answer)
- groupBy
Correct answer: fold
`fold` accumulates a value starting from an initial seed, applying an operation to each element and the accumulated value.
Question 6: What does `flatMap` do in Kotlin?
- Flattens a nested list into a single list
- Maps elements and flattens the resulting nested lists into one (Correct answer)
- Filters and maps simultaneously
- Groups elements into sublists
Correct answer: Maps elements and flattens the resulting nested lists into one
`flatMap` applies a transformation that returns a collection for each element, then flattens all results into a single list.
Which function creates an immutable list in Kotlin?