Discuss the significance and applications of extractors in Scala.

Instruction: Explain what extractors are and provide examples of their applications.

Context: This question is designed to test the candidate's knowledge of Scala's pattern matching mechanism, focusing on the role of extractors in deconstructing objects.

Updated

An extractor defines how a pattern recognizes and obtains information from a value, usually through unapply. It can expose a useful view without making the underlying representation part of the matching code.

object IntText {
  def unapply(text: String): Option[Int] =
    Option(text).flatMap(_.toIntOption)
}
def classify(text: String): String = text match {
  case IntText(value) if value > 0 => s"positive:$value"
  case IntText(value) => s"nonpositive:$value"
  case _ => "not an Int"
}
@main def extractorExample(): Unit = {
  assert(classify("12") == "positive:12")
  assert(classify("0") == "nonpositive:0")
  assert(classify("2147483648") == "not an Int")
  assert(classify(null) == "not an Int")
}

Some(value) means extraction succeeded; None means that pattern did not match. An extractor can also return a Boolean for a yes/no pattern or an option containing multiple extracted components. unapplySeq supports variable-length extraction. It need not have an apply method or be the inverse of a constructor. Extractor objects

Useful applications include parsing identifiers, matching regular-expression groups and hiding a domain representation. Case order and guards still matter. An extractor can be evaluated again by a later case, so keep it predictable and avoid expensive or effectful work where possible. The fallback handles unmatched inputs here; arbitrary extractors can still throw and are not automatically complete input validators.

Related Questions