In Scala, an extractor is an object that defines an ‘unapply‘ method to reverse the construction process, i.e., to extract the values used to construct an instance from that instance. The main purpose of extractors is to enable pattern matching on objects by extracting their components. When you use an extractor in a pattern, the ‘unapply‘ method is called to destructure the object and extract its components.
Here’s a brief overview of how extractors work in conjunction with pattern matching:
1. Define a class or case class.
2. Create an object with the same name (typically in the same source file) and define the ‘unapply‘ method inside this object (companion object).
3. Use the extractor object in pattern matching.
To illustrate this idea, let’s start with a simple example.
Suppose you have a case class ‘Person‘ representing a person with a first name and last name:
case class Person(firstName: String, lastName: String)
Now, let’s use extractors to enable pattern matching for the ‘Person‘ class. We’ll create a companion object for ‘Person‘ and define the ‘unapply‘ method inside it:
object Person {
def unapply(person: Person): Option[(String, String)] = {
Some((person.firstName, person.lastName))
}
}
The ‘unapply‘ method takes a ‘Person‘ instance as input and returns an ‘Option‘ containing a tuple with the first name and the last name. If the input person is invalid or couldn’t be deconstructed, the method should return ‘None‘.
Now that we have an extractor, we can use it in pattern matching as follows:
val person = Person("John", "Doe")
person match {
case Person(firstName, lastName) => println(s"First name: $firstName, Last name: $lastName")
case _ => println("Not a person instance")
}
When the pattern ‘case Person(firstName, lastName)‘ is matched, the ‘unapply‘ method of the ‘Person‘ object is called to extract the ‘firstName‘ and ‘lastName‘ components of the ‘person‘ instance. The extracted components will then be assigned to the ‘firstName‘ and ‘lastName‘ variables, which can be used in the subsequent code block.
In summary, extractors in Scala are objects with an ‘unapply‘ method that enables deconstruction of objects for use in pattern matching. The ‘unapply‘ method is responsible for extracting the relevant components of an object, allowing for more elegant and readable pattern-matching code.