Scala Functional Programming in Scala 1 — Questions and Answers
Question 1: What is a pure function in Scala functional programming?
- A function with no parameters
- A function that always returns the same output for the same input and has no side effects (Correct answer)
- A function defined inside an object
- A function that returns Unit
Correct answer: A function that always returns the same output for the same input and has no side effects
A pure function always produces the same output for the same input and does not cause any observable side effects.
Question 2: Which Scala method applies a function to every element of a collection and returns a new collection?
- forEach
- filter
- map (Correct answer)
- reduce
Correct answer: map
`map` transforms each element of a collection by applying a function and returns a new collection of the results.
Question 3: What is a higher-order function in Scala?
- A function that runs on multiple cores
- A function that takes other functions as parameters or returns a function (Correct answer)
- A function defined at the top level
- A recursive function
Correct answer: A function that takes other functions as parameters or returns a function
Higher-order functions accept functions as arguments or return functions, enabling powerful functional composition patterns.
Question 4: Which operator is used for function composition in Scala?
- >>
- andThen or compose (Correct answer)
- ->
- ++
Correct answer: andThen or compose
Scala's `Function1` provides `compose` and `andThen` methods to chain functions together in different orders.
Question 5: What does `flatMap` do differently than `map` in Scala?
- flatMap only works on Options
- flatMap applies a function returning a collection and flattens the result (Correct answer)
- flatMap ignores None values
- flatMap applies the function in reverse
Correct answer: flatMap applies a function returning a collection and flattens the result
`flatMap` applies a function that returns a collection to each element and then flattens all results into a single collection.
Question 6: What is tail recursion in Scala and why is it important?
- Recursion on the last element
- Recursion where the recursive call is the final operation, allowing stack optimization (Correct answer)
- Recursion limited to tail collections
- Recursion in companion objects
Correct answer: Recursion where the recursive call is the final operation, allowing stack optimization
Tail recursion allows the Scala compiler to optimize recursive calls into loops, preventing stack overflow for deep recursion.
What is a pure function in Scala functional programming?