You are on page 1of 2

Bala's Blog

Java, Big Data and Technology

POSTED BY

BALACHANDAR
POSTED ON

MARCH 23, 2019


POSTED UNDER

GENERAL, SCALA
COMMENTS

LEAVE A COMMENT

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

Scala (h ps://dkbalachandar.wordpress.com/tag/scala/)

Create a free website or blog at WordPress.com.

You might also like