Kotlin Kotlin Collections and Generics 2 — Questions and Answers
Question 1: What does `associateBy` do in Kotlin collections?
- Creates a Map from a collection using a key selector (Correct answer)
- Groups elements into a set
- Associates two collections by index
- Creates a bidirectional map
Correct answer: Creates a Map from a collection using a key selector
`associateBy` transforms a collection into a `Map<K, T>` using a key selector, with each element as the value.
Question 2: What is the difference between `any` and `all` in Kotlin collections?
- `any` checks all elements, `all` checks one
- `any` returns true if at least one element matches; `all` returns true only if every element matches (Correct answer)
- They are identical
- `any` works on sets, `all` works on lists
Correct answer: `any` returns true if at least one element matches; `all` returns true only if every element matches
`any` returns true if at least one element satisfies the predicate; `all` returns true only if every element satisfies it.
Question 3: What does `partition` do in Kotlin?
- Splits a collection into equal-sized chunks
- Splits a collection into two lists: matches and non-matches based on a predicate (Correct answer)
- Divides elements among multiple threads
- Removes every other element
Correct answer: Splits a collection into two lists: matches and non-matches based on a predicate
`partition` returns a `Pair<List<T>, List<T>>` where the first list contains elements matching the predicate and the second contains the rest.
Question 4: What is the purpose of generics in Kotlin?
- To allow functions to accept any number of parameters
- To enable type-safe reusable code that works with different types (Correct answer)
- To make classes serializable
- To avoid using nulls
Correct answer: To enable type-safe reusable code that works with different types
Generics allow writing type-safe classes and functions that work across different types without duplicating code.
Question 5: What does `out T` (covariance) mean in Kotlin generics?
- T can only be used as a parameter type
- T can only be produced (returned), making the generic covariant (Correct answer)
- T must implement Comparable
- T can be mutated inside the class
Correct answer: T can only be produced (returned), making the generic covariant
The `out` modifier makes a type parameter covariant — the generic can only produce values of type T, not consume them.
Question 6: What does `in T` (contravariance) mean in Kotlin generics?
- T can only be produced from the class
- T can only be consumed (accepted as input), making the generic contravariant (Correct answer)
- T is an optional type
- T must be nullable
Correct answer: T can only be consumed (accepted as input), making the generic contravariant
The `in` modifier makes a type parameter contravariant — the generic can only consume values of type T, not produce them.
What does `associateBy` do in Kotlin collections?