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 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)
println(message2)
|
Output:
John is an adult
Not an adult
Similar Reads
Iterators in Scala
An iterator is a way to access elements of a collection one-by-one. It resembles to a collection in terms of syntax but works differently in terms of functionality. An iterator defined for any collection does not load the entire collection into the memory but loads elements one after the other. Ther
5 min read
Scala | Literals
Any constant value which can be assigned to the variable is called as literal/constant. The literals are a series of symbols utilized for describing a constant value in the code. There are many types of literals in Scala namely Character literals, String literals, Multi-Line String literals, Boolean
4 min read
Scala Identifiers
In programming languages, Identifiers are used for identification purpose. In Scala, an identifier can be a class name, method name, variable name or an object name. For example : class GFG{ var a: Int = 20 } object Main { def main(args: Array[String]) { var ob = new GFG(); } } In the above program
3 min read
Enumeration in Scala
An enumerations serve the purpose of representing a group of named constants in a programming language. Refer Enumeration (or enum) in C and enum in Java for information on enumerations. Scala provides an Enumeration class which we can extend in order to create our enumerations. Declaration of enume
3 min read
Scala | Product3
Product3 is a trait in Scala, which is a Cartesian product of three elements. The Linear Supertypes here are Product, Equals, and Any and the known subclass here is Tuple3. It extends the trait Product i.e, trait Product3[+T1, +T2, +T3] extends Product Where, T1, T2, and T3 are the used parameter ty
2 min read
Abstract Classes in Scala
Abstraction is the process to hide the internal details and showing only the functionality. In Scala, abstraction is achieved by using an abstract class. The working of the Scala abstract class is similar to Java abstract class. In Scala, an abstract class is constructed using the abstract keyword.
5 min read
Scala Lists
A list is a collection which contains immutable data. List represents linked list in Scala. The Scala List class holds a sequenced, linear list of items. Following are the point of difference between lists and array in Scala: Lists are immutable whereas arrays are mutable in Scala. Lists represents
5 min read
Parameterless Method in Scala
Prerequisites - Scala | Functions A parameterless method is a function that does not take parameters, defined by the absence of any empty parenthesis. Invocation of a paramaterless function should be done without parenthesis. This enables the change of def to val without any change in the client cod
2 min read
Scala List +() operator with example
The +() operator in Scala is utilized to append an element to the list. Method Definition: def +(elem: A): List[A] Return Type: It returns a list of the stated elements after appending it to an another element. Example #1: // Scala program of +() // method // Creating object object GfG { // Main met
1 min read
Scala List :::() operator with example
The :::() operator in Scala is utilized to join the List in the argument to the another List. Method Definition: def :::(prefix: List[A]): List[A] Return Type: It returns a list after joining one list to the another one. Example #1: // Scala program of :::() // method // Creating object object GfG {
1 min read