Scala Extractors

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 :

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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"))
    }
}

chevron_right


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 :

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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))
    }
}

chevron_right


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:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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
    }

    chevron_right

    
    

    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:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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))
      
        }
    }

    chevron_right

    
    

    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.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.