Home »
Scala
Scala Extractors
By IncludeHelp Last updated : October 28, 2024
What is an Extractor in Scala
An extractor is a special type of object that has some special methods. These methods are: apply() and unapply().
- The apply() method of extractor object is used to feeding values for the object, it takes parameter values, formats them and adds them to the object.
- The unapply() method of extractor object is used to delete values from the object, it matches the value and removes them from the object list.
Working of Extractors
Let's take an example of an object that apply() as well as unapply() method. The apply() method takes arguments and adds them to class. The unapply() does the exact opposite, it takes arguments, matches them and then deletes, i.e. deconstructs.
Example of Scala Extractor
The following is an example of Scala extractor using apply and unapply methods in Scala's Student object:
object Student {
def main(args: Array[String]): Unit = {
def apply(name: String, result: String): String = {
name + " is " + result
}
def unapply(x: String): Option[(String, String)] = {
val y = x.split(" is ")
if (y.length == 2 && y(1) == "Pass") {
Some(y(0), y(1))
} else {
None
}
}
println("The Apply method returns: " + apply("Ram", "Pass"))
println("The Unapply method returns: " + unapply("Ram is Pass").getOrElse("No match"))
}
}
Output
The Apply method returns : Ram is Pass
The Unapply method returns : Some((Ram,Pass))
Explanation
The unapply() method here, checking if the student is passed and removes it based on the result.