top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Explain the concept and usage of an extractor in Scala?

+1 vote
373 views
Explain the concept and usage of an extractor in Scala?
posted Oct 13, 2016 by Karthick.c

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

An extractor in Scala is an object that has a method called unapply as one of its members. The purpose of that unapply method is to match a value and take it apart. Often, the extractor object also defines a dual method apply for building values, but this is not required.

Example

Let us take an example of object defines 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 you can write Test ("QueryHome", "gmail.com") to construct the string "QueryHome@gmail.com".

The unapply method is what turns Test class into an extractor and it reverses the construction process of apply. Where apply takes two strings and forms an email address string out of them, unapply takes an email address and returns potentially two strings: the user and the domain of the address.

The unapply must also handle the case where the given string is not an email address. That's why unapply returns an Option-type over 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. Here are some examples as follows.

Syntax

unapply("QueryHome@gmail.com") equals Some("QueryHome", "gmail.com")
unapply("QueryHome") equals None

Following example program shows an extractor object for email addresses.

Example

object Demo {
   def main(args: Array[String]) {
      println ("Apply method : " + apply("QueryHome", "gmail.com"));
      println ("Unapply method : " + unapply("QueryHome@gmail.com"));
      println ("Unapply method : " + unapply("QueryHome"));
   }

   // The injection method (optional)
   def apply(user: String, domain: String) = {
      user +"@"+ domain
   }

   // The extraction method (mandatory)
   def unapply(str: String): Option[(String, String)] = {
      val parts = str split "@"

      if (parts.length == 2){
         Some(parts(0), parts(1)) 
      } else {
         None
      }
   }
}

Command

\>scalac Demo.scala
\>scala Demo

Output

Apply method : QueryHome@gmail.com
Unapply method : Some((QueryHome,gmail.com))
Unapply method : None

Pattern Matching with Extractors

When an instance of a class is followed by parentheses with a list of zero or more parameters, the compiler invokes the apply method on that instance. We can define apply both in objects and in classes.

As mentioned above, the purpose of the unapply method is to extract a specific value we are looking for. It does the opposite operation apply does. When comparing an extractor object using the match statement the unapply method will be automatically executed.

Example

object Demo {
   def main(args: Array[String]) {
      val x = Test(5)
      println(x)

      x match {
         case Test(num) => println(x+" is bigger two times than "+num)

         //unapply is invoked
         case _ => println("i cannot calculate")
      }
   }
   def apply(x: Int) = x*2
   def unapply(z: Int): Option[Int] = if (z%2==0) Some(z/2) else None
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

10
10 is bigger two times than 5
answer Oct 18, 2016 by Shyam
Similar Questions
+1 vote

What is REPL in Scala? What is the use of Scala’s REPL? How to access Scala REPL from CMD Prompt?

0 votes

Explain the main difference between List and Stream in Scala Collection API? How do we prove that difference? When do we choose Stream?

...