Scala Extractor is defined as an object which has a method named unapply as one of its part. Extractors can be utilized in Pattern Matching. The unapply method will be executed spontaneously, While comparing the Object of an Extractor in Pattern Matching.
Below is the example of Extractor with pattern matching.
Example #1:
// 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 } |
5.0 The value is: 1.0
In above example, object name is GFG also we are using unapply method and applying case class with match expression.
Example #2:
// Scala program of extractors // with pattern matching // Creating object object GFG { // Main method def main(args: Array[String]) { val x = GFG(15) println(x) x match { case GFG(num) => println(x + " is bigger two times than " + num) // Unapply is invoked case _ => println("not calculated") } } def apply(x: Int) = x * 2def unapply(z: Int): Option[Int] = if (z % 2 == 0) Some(z/2) else None } |
30 30 is bigger two times than 15
When comparing an extractor object using the match statement the unapply method will be automatically executed.
Note: A Case class already has an Extractor in it so, it can be utilized spontaneously with Pattern Matching.
Recommended Posts:
- Scala short <(x: Short): Boolean
- Scala short <(x: Char): Boolean
- Scala Extractors
- Scala | Partially Applied functions
- Scala String indexOf(String str) method with example
- Scala String contentEquals() method with example
- Scala Keywords
- Scala Int /(x: Int) method with example
- Scala Int /(x: Short) method with example
- Program to print Java Set of characters in Scala
- Scala Map size() method with example
- Scala SortedMap addString() method with a start, a separator and an end with example
- Scala Iterator addString() method with example
- Scala String substring(int beginIndex, int endIndex) method with example
- Scala | Functions Call-by-Name
- Program to convert Java list to an iterator in Scala
- Scala Set &() method with example
- Scala | Type Inference
- Program to convert Java set of Shorts to an Indexed Sequence in Scala
- Scala Int <(x: Char) method with example
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

