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
object Name
{
def main(args : Array[String])
{
def apply(firstname : String, lastname : String) =
{
firstname + "kumari" + lastname
}
def unapply(x : String) : Option[(String, String)] =
{
val y = x.split( "kumari" )
if (y.length == 2 )
{
Some(y( 0 ), y( 1 ))
}
else
None
}
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
object GfG
{
def main(args : Array[String])
{
def apply(q : Double) : Double = q * 10
def unapply(r : Int) : Option[Int] = {
if (r % 5 == 0 )
{
Some(r * 5 )
}
else
None
}
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
object GfG
{
def main(args : Array[String])
{
val x = GfG( 25 )
println(x)
x match
{
case GfG(y) => println( "The value is: " +y)
case _ => println( "Can't be evaluated" )
}
}
def apply(x : Double) = x / 5
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
object GfG
{
def main(args : Array[String])
{
def unapply(x : Int) : Boolean = {
if (x % 3 == 0 )
{
true
}
else
false
}
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 message 1 = john match {
case Adult(name) => s "$name is an adult"
case _ => "Not an adult"
}
val message 2 = alice match {
case Adult(name) => s "$name is an adult"
case _ => "Not an adult"
}
println(message 1 )
println(message 2 )
|
Output:
John is an adult
Not an adult
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
09 Apr, 2023
Like Article
Save Article