Scala Functional Programming in Scala 2 — Questions and Answers
Question 1: What does the `filter` method do on a Scala collection?
- Transforms each element
- Returns only elements satisfying a predicate (Correct answer)
- Sorts elements
- Removes duplicates
Correct answer: Returns only elements satisfying a predicate
`filter` returns a new collection containing only the elements for which the given predicate function returns true.
Question 2: What is a closure in Scala?
- A sealed class
- A function that captures variables from its enclosing scope (Correct answer)
- A private object
- An anonymous trait
Correct answer: A function that captures variables from its enclosing scope
A closure is a function that references variables from its surrounding lexical scope, carrying those bindings with it.
Question 3: Which Scala method combines all elements of a collection into a single value?
- collect
- flatten
- fold or reduce (Correct answer)
- zip
Correct answer: fold or reduce
`fold` and `reduce` are aggregation methods that apply a binary operation across a collection to produce a single accumulated result.
Question 4: What is referential transparency in functional programming?
- The ability to reference private fields
- An expression that can be replaced by its value without changing program behavior (Correct answer)
- Functions that return references
- Transparent visibility modifiers
Correct answer: An expression that can be replaced by its value without changing program behavior
Referential transparency means any expression can be substituted with its evaluated result without altering the program's behavior.
Question 5: How are anonymous functions (lambdas) defined in Scala?
- function(x) => x + 1
- lambda x: x + 1
- (x: Int) => x + 1 (Correct answer)
- \x -> x + 1
Correct answer: (x: Int) => x + 1
Scala anonymous functions use the fat arrow `=>` syntax with optional parameter types: `(x: Int) => x + 1`.
Question 6: What does `collect` do on a Scala collection?
- Gathers futures
- Applies a partial function to elements, returning only defined results (Correct answer)
- Collects all None values
- Groups elements by key
Correct answer: Applies a partial function to elements, returning only defined results
`collect` applies a partial function to a collection and returns only the elements for which the partial function is defined.
What does the `filter` method do on a Scala collection?