Explain the role and use of 'extractors' in Scala for pattern matching.
Instruction: Describe how extractors are used in Scala's pattern matching and provide an example.
Updated
An extractor supplies a pattern through an unapply method. It can recognize a value and expose a useful view without requiring the value to be a case class or exposing all of its representation.
final class Span(val start: Int, val end: Int)
object NonEmptySpan {
def unapply(span: Span): Option[(Int, Int)] =
Option(span).filter(s => s.end > s.start)
.map(s => (s.start, s.end))
}
def describe(span: Span): String = span match {
case NonEmptySpan(start, end) => s"[$start, $end)"
case _ => "not a nonempty span"
}
@main def extractorViewExample(): Unit = {
assert(describe(new Span(2, 5)) == "[2, 5)")
assert(describe(new Span(2, 2)) == "not a nonempty span")
assert(describe(null) == "not a nonempty span")
}
Some((start, end)) makes the pattern match and binds its two components; None makes it fail. This extractor deliberately has no apply constructor and is not an inverse construction operation. Extractor objects
Other extractor shapes can return a Boolean or support variable-length extraction through unapplySeq. Keep the recognition rule clear and preferably free of side effects: pattern matching can invoke extractors as it tries alternatives, and a thrown exception is not automatically converted to a failed match. This example handles a null span explicitly and compares endpoints without subtracting them, avoiding an overflowing length calculation.