Scala – Extractors

  • date 28th April, 2021 |
  • by Prwatech |
  • 0 Comments

In Scala Extractor is characterized as an item which has a technique named unapply as one of its part. This technique extracts an object and returns back the characteristics. This strategy is likewise utilized in Pattern matching and Partial functions. Extractors additionally clarify apply method, which takes the arguments and develops an object thus, it’s useful in building values. The unapply technique reverses the development procedure of the apply method.

use case 1:

scala> def apply(fname:String,lname:String)={

     | fname+” “+lname

     | }

scala> def unapply(str:String):Option[(String,String)]={

     | val parts=str split ” “

     | if(parts.length==2){

     | Some(parts(0),parts(1))

     | }else{

     | None

     | }

     | }

scala> apply(“Mark”,”Zuckerberg”)

scala> unapply(“Mark Zuckerberg”)

scala> unapply(“MarkZuckerberg”)

use case 2:

     // Creating object
     object prwatech {
     // Main method
     def main(args: Array[String])
    {
    // Assigning value to the
    // object
    val x = prwatech(50)

    // Displays output of the
    // Apply method
    println(x)

    // Applying pattern matching 
    x match
    {

        // unapply method is called
        case prwatech(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:

10.0
The value is: 2.0

use case 3:

// Scala program of extractors
 to return a Boolean type

// Main method
// Creating object
object PRWATECH
{
def main(args: Array[String]) 
{

    // Defining unapply method
    def unapply(x:Int): Boolean = {

        if (x % 5 == 0)
        {
            true
        }
        else
                false
    }

    // Displays output in Boolean type
    println ("Unapply method returns : " + unapply(16))
    println ("Unapply method returns : " + unapply(35))

}
}

output:

Unapply method returns : false
Unapply method returns : true

Quick Support

image image