Skip to content
Related Articles

Related Articles

Scala Extractors
  • Last Updated : 08 Apr, 2019

In Scala Extractor is defined as an object which has a method named unapply as one of its part. This method extracts an object and returns back the attributes. This method is also used in Pattern matching and Partial functions. Extractors also explains apply method, which takes the arguments and constructs an object so, it’s helpful in constructing values. The unapply method reverses the construction procedure of the apply method.
 
The return type of the unapply method can be selected like stated below:

  • If it is a checking procedure then return a Boolean Type.
  • If the procedure is returning only one sub-value of type T, then return an Option[T].
  • If the procedure is returning various sub-values of type T1, T2, …, Tn then return an optional tuple i.e, Option[(T1, T2, …, Tn)].
  • If the procedure returns an unpredictable number of values, then the extractors can be defined with an unapplySeq that returns an Option[Seq[T]].

Example :




// Scala program of extractors
  
// Creating object
object Name 
{
  
    // Main method
    def main(args: Array[String]) 
    {
      
        // Defining apply method
        def apply(firstname: String, lastname: String) =
        {
            firstname +"kumari"+ lastname
      
        }
  
        // Defining unapply method
        def unapply(x: String): Option[(String, String)] =
        {
      
            // Applying a method split
            val y = x.split("kumari")
      
            if (y.length == 2)
            {
                  
                Some(y(0), y(1)) 
              
            }
            else
                    None
      
        }
      
        // Displays output
        println ("The Apply method returns : "
                        apply("Nidhi", "Singh"))
        println ("The Unapply method returns : "
                        unapply("NidhikumariSingh"))
    }
}
Output:
The Apply method returns : NidhikumariSingh
The Unapply method returns : Some((Nidhi, Singh))

Here, this example shows an extractor object for Name.The object Name defines two methods apply and unapply. The apply method accepts the arguments specified within the parenthesis and also creates a value as specified in the method. The first and last name combined together with kumari(middle name) in between is returned. The unapply method breaks the arguments as specified and returns firstname object into an extractor . It returns a pair of strings if as an argument, the first name and last name is passed else returns none.
Example :




// Scala program of extractors
  
// Creating object
object GfG
{
  
    // Main method
    def main(args: Array[String]) 
    {
      
        // Defining apply method
        def apply(q: Double): Double = q * 10
  
        // Defining unapply method
        def unapply(r: Int): Option[Int] = {
      
            if (r % 5 == 0)
            {
                Some(r * 5
            }
            else
                None
      
        }
      
        // Displays output
        println ("The Apply method returns : " + apply(20))
        println ("The Unapply method returns : " + unapply(35))
    }
}
Output:



The Apply method returns : 200.0
The Unapply method returns : Some(175)

Here, this example shows an extractor object for GFG.The object GFG defines two methods apply and unapply. The apply method accepts the arguments of double type . When we call apply method then the passed argument is multiplied by 10 and returns the multiplied number. The unapply method breaks the arguments if passed value is divisible by 5 than passed value is multiplied by 5 and returns that(r*5) else returns none.

Usage Of Scala Extractors

  • Using Extractors with Pattern Matching:
    Extractors can be utilized in Pattern Matching. While comparing the Object of an Extractor in Pattern Matching, the unapply method will be executed spontaneously.
    Example:




    // Scala program of extractors 
    // with pattern matching
      
    // Creating object
    object GfG 
    {
      
        // Main method
        def main(args: Array[String]) 
        {
      
            // Assigning value to the
            // object
            val x = GfG(25)
      
            // Displays output of the
            // Apply method
            println(x)
      
            // Applying pattern matching 
            x match
            {
      
                // unapply method is called
                case GfG(y) => println("The value is: "+y)
                case _ => println("Can't be evaluated")
          
            }
        }
          
        // Defining apply method
        def apply(x: Double) = x / 5
      
        // Defining unapply method
        def unapply(z: Double): Option[Double] =
      
            if (z % 5 == 0
            {
                Some(z/5
            }
          
            else None
    }
    Output:
    5.0
    The value is: 1.0
    

    Note: A Case class already has an Extractor in it so, it can be utilized spontaneously with Pattern Matching.

  • Using Extractors for testing:
    In order to use an Extractor for testing, a Boolean type is returned.
    Example:




    // Scala program of extractors
    // to return a Boolean type
      
    // Creating object
    object GfG 
    {
      
        // Main method
        def main(args: Array[String]) 
        {
      
            // Defining unapply method
            def unapply(x:Int): Boolean = {
          
                if (x % 3 == 0)
                {
                    true
                }
                else
                        false
            }
              
            // Displays output in Boolean type
            println ("The Unapply method returns : " + unapply(12))
            println ("The Unapply method returns : " + unapply(35))
      
        }
    }
    Output:
    true
    false
    

Here, The object GFG defines a method unapply. during the calling of unapply method a perameter is passed if the value is divided by 3 than returns true else returns false.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :