Scala Scala Collections 1 — Questions and Answers
Question 1: What is the difference between a Scala `List` and `Vector`?
- List is mutable; Vector is immutable
- List has O(1) prepend; Vector has O(log n) random access and is better for large collections (Correct answer)
- Vector only holds Int values
- List supports parallel operations; Vector does not
Correct answer: List has O(1) prepend; Vector has O(log n) random access and is better for large collections
Scala's immutable `List` provides O(1) prepend but O(n) random access, while `Vector` provides effectively O(1) random access for large collections.
Question 2: How do you add an element to the front of a Scala immutable List?
- list.add(elem)
- list.prepend(elem)
- elem :: list (Correct answer)
- list + elem
Correct answer: elem :: list
The `::` cons operator prepends an element to a Scala List, returning a new List with the element at the front.
Question 3: What does `groupBy` do on a Scala collection?
- Sorts elements
- Groups elements into a Map by the result of a key function (Correct answer)
- Removes duplicates
- Partitions into exactly two groups
Correct answer: Groups elements into a Map by the result of a key function
`groupBy` applies a function to each element and returns a `Map` from keys to collections of elements sharing that key.
Question 4: Which Scala collection type guarantees uniqueness of elements?
- Seq
- List
- Set (Correct answer)
- Queue
Correct answer: Set
Scala's `Set` enforces element uniqueness, ignoring duplicate insertions based on the `equals` and `hashCode` of elements.
Question 5: What is the purpose of `foldLeft` in Scala?
- Folds a list in half
- Accumulates a result from left to right using a binary function and an initial value (Correct answer)
- Flattens a nested list
- Folds the type hierarchy
Correct answer: Accumulates a result from left to right using a binary function and an initial value
`foldLeft(init)(f)` starts with an initial value and applies a binary function from left to right across the collection.
Question 6: What does `partition` return on a Scala collection?
- A single filtered collection
- A tuple of two collections: elements satisfying a predicate and those that don't (Correct answer)
- A Map from Boolean to collections
- The first element matching a predicate
Correct answer: A tuple of two collections: elements satisfying a predicate and those that don't
`partition` splits a collection into a tuple `(matching, notMatching)` based on a boolean predicate.
What is the difference between a Scala `List` and `Vector`?