Scala Extractor Objects

An Extractor object is an object with an unapply method which takes an object and tries to give back its arguments.

As we all know that apply method of an Object takes arguments and creates an object and the unapply method will do the reverse.

Lets see this with an example.



object Customer {

  def apply(firstName: String, lastName: String) = firstName + "," + lastName

  def unapply(customerName: String): Option[String] = {
    val nameArray = customerName.split(",")
    if (nameArray.nonEmpty) nameArray.headOption else None
  }

  def main(args: Array[String]): Unit = {
    val customer = Customer("Balachandar", "Kuppusamy")

    customer match {
      case Customer(name) => println(s"FirstName is:$name")
      case _ => println("Could not extract Name")
    }
  }
}


In the above code, Customer is an object and the apply method takes first and last names and combine those names with a comma symbol and the unapply method takes the name and split it and then return the first name as an output.

Customer(“Balachandar”, “Kuppusamy”) is a shorthand for calling Customer.apply(“Balchandar”, “Kuppusamy”) and case Customer(name) is a shorthand for calling Customer.apply(name).

The output of the above program will look like below,


FirstName is:Balachandar