Scala Pattern Matching and Case Classes 1 — Questions and Answers
Question 1: How is pattern matching performed in Scala?
- using switch-case
- using match-case (Correct answer)
- using if-else chains
- using instanceof checks
Correct answer: using match-case
Scala uses `match-case` blocks for pattern matching, providing a powerful and expressive alternative to switch statements.
Question 2: What keyword defines a case class in Scala?
- data class
- record
- case class (Correct answer)
- value class
Correct answer: case class
Scala's `case class` automatically generates `equals`, `hashCode`, `toString`, and an `unapply` method for pattern matching.
Question 3: What does the `_` pattern mean in a Scala match expression?
- Match only null
- Match the head element
- Match any value (wildcard) (Correct answer)
- Match empty collections
Correct answer: Match any value (wildcard)
The `_` wildcard pattern matches any value and is typically used as the default catch-all case in a match expression.
Question 4: Which method does a case class automatically generate for pattern matching?
- apply
- unapply (Correct answer)
- extract
- match
Correct answer: unapply
The compiler auto-generates `unapply` for case classes, which the pattern matcher calls to destructure an object.
Question 5: Can you pattern match on the type of a value in Scala?
- No, use instanceof instead
- Yes, using type patterns like `case x: String =>` (Correct answer)
- Only with sealed traits
- Only at compile time
Correct answer: Yes, using type patterns like `case x: String =>`
Scala supports typed patterns such as `case x: String =>` to match and bind a variable when the value is of a given type.
Question 6: What is an extractor object in Scala?
- An object that extends Iterator
- An object with an `unapply` method used for custom pattern matching (Correct answer)
- An object that reads from files
- A singleton that wraps Option
Correct answer: An object with an `unapply` method used for custom pattern matching
An extractor is an object providing an `unapply` method that deconstructs values, enabling custom patterns in match expressions.
How is pattern matching performed in Scala?