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]].
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.
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.
- 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.
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.
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.