Scala Scala Collections 3 — Questions and Answers
Question 1: What does `scanLeft` do in Scala compared to `foldLeft`?
- scanLeft only works on infinite lists
- scanLeft returns all intermediate accumulator values, not just the final result (Correct answer)
- scanLeft is more efficient than foldLeft
- scanLeft applies function in reverse
Correct answer: scanLeft returns all intermediate accumulator values, not just the final result
`scanLeft` produces a collection of all intermediate accumulator values including the initial value, while `foldLeft` returns only the final value.
Question 2: What is a `SortedMap` in Scala?
- A Map that sorts values
- A Map that iterates keys in sorted order (Correct answer)
- A mutable tree map
- A Map with case-insensitive keys
Correct answer: A Map that iterates keys in sorted order
`SortedMap` maintains keys in sorted order (using an implicit `Ordering`), iterating entries from smallest to largest key.
Question 3: How do you safely access a Map value in Scala without risking an exception?
- map.get(key) returns Option (Correct answer)
- map.apply(key) returns Option
- map.find(key) returns Option
- map.lookup(key) returns Option
Correct answer: map.get(key) returns Option
`map.get(key)` returns `Some(value)` if the key exists or `None` if it doesn't, avoiding `NoSuchElementException`.
Question 4: What does `zip` produce when applied to collections of different lengths?
- A collection as long as the longer one, with nulls for missing values
- A collection as long as the shorter one, dropping excess elements (Correct answer)
- A compilation error
- An exception at runtime
Correct answer: A collection as long as the shorter one, dropping excess elements
`zip` truncates to the shorter collection's length, producing only pairs where both collections have elements.
Question 5: What is the difference between `map` and `foreach` on a Scala collection?
- map is for mutable collections; foreach is for immutable
- map returns a new transformed collection; foreach returns Unit and is used for side effects (Correct answer)
- foreach is faster than map
- map only works on Lists
Correct answer: map returns a new transformed collection; foreach returns Unit and is used for side effects
`map` transforms elements and returns a new collection, while `foreach` iterates for side effects and returns `Unit`.
Question 6: What does `flatten` do on a `List[List[Int]]` in Scala?
- Removes duplicates
- Transposes rows and columns
- Concatenates all inner lists into a single flat list (Correct answer)
- Sorts all elements
Correct answer: Concatenates all inner lists into a single flat list
`flatten` collapses one level of nesting, combining all inner collections into a single collection.
What does `scanLeft` do in Scala compared to `foldLeft`?