An extractor in Scala programming language is an object which has a method named unapply as one of its members. The main purpose of this unapply method is to match a value and take it apart. Normally, the extractor object also specifies a dual method apply for building values, which is not required.
Let see an example of object specifying both apply and unapply methods. The apply method has the same meaning as always: it turns Test into an object that can be applied to arguments in parentheses in the same way a method is applied. So we can write Test ("Zara", "gmail.com") inorder to construct the string "Zara@gmail.com".
The unapply method is used for turning the Test class into an extractor and it will reverse the construction process of apply. Where apply takes two strings and forms an email address string out of them, unapply will take an email address and it will return potentially two strings: the user and the domain of the address.
The unapply method must also handle the cases when the given string is not an email address. So, unapply method will return an Option-type over the pairs of strings. Its result is either Some (user, domain) if the string str is an email address with the given user and domain parts, or None, if str is not an email address. Below given are few examples as stated.
Following example program shows an extractor object for email addresses.
We need to save the above program inDemo.scala. The below commands are used to compile and run this program.
When an instance of a class is followed by parentheses with a list of zero or more parameters, the compiler calls the apply method on that instance. We can specify apply both in objects and in classes.
As mentioned earlier, the main purpose of this unapply method is to extract a specific value that we are searching for. It does the opposite operation apply does. When we will be comparing an extractor object with the aid of the match statement , the unapply method will get automatically executed.
Try the below sample example program.
We need to save the above program in Demo.scala. The below commands are used to compile and run this program.
Scala Related Interview Questions
|Python Interview Questions||Adv Java Interview Questions|
|Hadoop Interview Questions||Ruby on Rails Interview Questions|
|Apache Cassandra Interview Questions||Prolog Interview Questions|
|Apache Spark Interview Questions||Apache Solr Interview Questions|
|NoSQL Interview Questions||Spark SQL Programming Interview Questions|
|MongoDB Interview Questions|
All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.