Open In App

Scala Extractors

Improve
Improve
Like Article
Like
Save
Share
Report

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




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




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




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




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

The Unapply method returns : true
The Unapply method returns : false

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

Scala Extractors are objects that can be used to deconstruct objects and extract their parts in a flexible and concise way. They are often used in pattern matching, a powerful feature of Scala that allows developers to match objects against a set of patterns and execute code based on the matching result.

Extractors are created by defining an object with an unapply method. This method takes an object and returns an optional tuple of values that represent the extracted parts of the object. If the object cannot be deconstructed into the desired parts, the unapply method returns None.

Sure! Here’s an example code that demonstrates the use of an Extractor to deconstruct a case class object:

Scala




case class Person(name: String, age: Int)
 
object Adult {
  def unapply(person: Person): Option[String] = {
    if (person.age >= 18) Some(person.name)
    else None
  }
}
 
val john = Person("John", 25)
val alice = Person("Alice", 17)
 
val message1 = john match {
  case Adult(name) => s"$name is an adult"
  case _ => "Not an adult"
}
 
val message2 = alice match {
  case Adult(name) => s"$name is an adult"
  case _ => "Not an adult"
}
 
println(message1) // Output: John is an adult
println(message2) // Output: Not an adult


 Output:

John is an adult
Not an adult
 



Last Updated : 09 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads