Scala Extractors - Scala

What is Scala Extractor?

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.

Example

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.

Syntax

Following example program shows an extractor object for email addresses.

Example

We need to save the above program inDemo.scala. The below commands are used to compile and run this program.

Command

Output

Pattern Matching with Extractors

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.

Example

We need to save the above program in Demo.scala. The below commands are used to compile and run this program.

Command

Output

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Scala Topics