Kotlin Kotlin Collections and Generics 1 — Questions and Answers
Question 1: Which Kotlin collection is immutable by default?
- ArrayList
- MutableList
- List (Correct answer)
- LinkedList
Correct answer: List
In Kotlin, `List` is a read-only interface that does not expose mutation methods; `MutableList` is its mutable counterpart.
Question 2: How do you create a mutable list in Kotlin?
- listOf()
- mutableListOf() (Correct answer)
- arrayListOf() only
- MutableList()
Correct answer: mutableListOf()
`mutableListOf()` creates a `MutableList<T>` backed by an `ArrayList`, allowing add, remove, and update operations.
Question 3: What does the `groupBy` function do in Kotlin?
- Sorts elements into groups by value
- Groups elements into a map by a key selector function (Correct answer)
- Removes duplicate elements
- Partitions elements into two lists
Correct answer: Groups elements into a map by a key selector function
`groupBy` returns a `Map<K, List<T>>` where each key maps to a list of elements matching that key from the key selector.
Question 4: Which function returns the first element matching a predicate or null in Kotlin?
- first()
- filter()
- find() (Correct answer)
- get()
Correct answer: find()
`find()` returns the first element satisfying the predicate, or null if no element matches, unlike `first()` which throws if not found.
Question 5: What does `flatMap` do in Kotlin?
- Flattens a list of lists into one list
- Maps each element and then flattens the resulting nested collections (Correct answer)
- Converts a map to a flat list
- Sorts and flattens a collection
Correct answer: Maps each element and then flattens the resulting nested collections
`flatMap` applies a transform that returns a collection for each element, then flattens all results into a single list.
Question 6: What is `Pair` in Kotlin?
- A mutable two-element list
- A data class holding two values of potentially different types (Correct answer)
- A map with two entries
- A tuple with two comparable values
Correct answer: A data class holding two values of potentially different types
`Pair<A, B>` is a simple data class that holds two values, accessible via `.first` and `.second`.
Which Kotlin collection is immutable by default?