Using Extractors with Pattern Matching In Scala
Last Updated :
02 Aug, 2019
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:
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
In above example, object name is GFG also we are using unapply method and applying case class with match expression.
Example #2:
object GFG
{
def main(args : Array[String])
{
val x = GFG( 15 )
println(x)
x match
{
case GFG(num) => println(x +
" is bigger two times than " + num)
case _ => println( "not calculated" )
}
}
def apply(x : Int) = x * 2
def unapply(z : Int) : Option[Int] = if (z % 2 == 0 )
Some(z/ 2 ) else None
}
|
Output:
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.
Share your thoughts in the comments
Please Login to comment...