Scala Pattern Matching and Case Classes 2 — Questions and Answers
Question 1: What is a sealed trait in Scala and why is it useful with pattern matching?
- A trait that cannot be mixed in
- A trait whose subclasses are defined in the same file, enabling exhaustive matching (Correct answer)
- A trait with private members
- A trait with no abstract methods
Correct answer: A trait whose subclasses are defined in the same file, enabling exhaustive matching
A sealed trait restricts all subclasses to the same file, allowing the compiler to warn about non-exhaustive match expressions.
Question 2: How do you match on a List's head and tail in Scala?
- case [h, t] =>
- case h :: t => (Correct answer)
- case (h, t) =>
- case head(h, t) =>
Correct answer: case h :: t =>
The cons operator `::` is used in patterns to destructure a List into its head element and its tail list.
Question 3: What happens if no pattern matches in a Scala match expression?
- The program silently continues
- It returns null
- A MatchError is thrown at runtime (Correct answer)
- The first case is used as default
Correct answer: A MatchError is thrown at runtime
If no case matches in a Scala match expression, a `MatchError` is thrown at runtime, so always include a default case.
Question 4: Which Scala feature lets you add a condition to a pattern match case?
- Pattern guard using `if` (Correct answer)
- Pattern filter
- Case annotation
- Where clause
Correct answer: Pattern guard using `if`
A pattern guard adds an `if condition` after the pattern in a case clause, further restricting when that arm is selected.
Question 5: What does `copy` do on a Scala case class?
- Creates a deep clone of a collection
- Returns a modified copy of the instance with specified fields changed (Correct answer)
- Copies the class definition
- Converts the case class to a Map
Correct answer: Returns a modified copy of the instance with specified fields changed
The auto-generated `copy` method creates a new case class instance with the same values, except for the fields you specify.
Question 6: How do you pattern match a Tuple2 in Scala?
- case Tuple(a, b) =>
- case (a, b) => (Correct answer)
- case [a, b] =>
- case a -> b =>
Correct answer: case (a, b) =>
Tuple patterns use parentheses to destructure a tuple into its components, e.g., `case (a, b) =>` matches a pair.
What is a sealed trait in Scala and why is it useful with pattern matching?