How to use extractors in Scala ?

 

This blog will guide you through the basic understanding of extractors in scala.

An extractor is an object that has an unapply method. It takes an object as an input and gives back arguments. Custom extractors are created using the unapply method. The unapply method is called extractor because it takes an element of the same set and extracts some of its parts,  apply method also called injection acts as a constructor, takes some arguments and yields an element of a given set.

A case class in Scala, by default implements, apply and unapply methods.

Case Classes are special because Scala automatically creates a companion object for them: a singleton object that contains not only an apply method for creating new instances of the case class but also an unapply method that needs to be implemented by an object in order for it to be an extractor.

apply”  method is called while instantiating case class :

val name = Blog.unapply(blog).get is same as:

 

Let’s understand extractors using examples:

The return type of an unapply should be chosen while keeping following things in mind:

  1. If it returns a single sub-value of type T, return a Option[T].
  2. If it is just a test, return a Boolean.
  3. If you want to return several sub-values T1,...,Tn, group them in an optional tuple Option[(T1,...,Tn)].

Let’s discuss all three points one by one:

When no value matches in case, match error is thrown.

SINGLE SUB-VALUE

val object = Math(2) expands to val object = Math.apply(2)

SEVERAL SUB-VALUES

BOOLEAN VALUE

If you have a variable number of argument values, scala gives an extractor method unapplySeq.

Let’s understand the order in which extractors are called:

 

EMailValidator(Twice(x @ UpperCase()), domain) order of calling is from left to right.

EmailValidator divides “DIDI@hotmail.com” into “DIDI” and “hotmail.com” (user and domain). Twice will be called on the user and unapply  method will convert it to “DI”. Uppercase will be called on DI and true will be returned. The result will be:

 match: DI in domain hotmail.com

Extractors do not expose the concrete representation of data. They enable patterns without any relation to the data type for the selected object.

Thanks for reading!

Written by 

Jyoti Sachdeva is a software consultant with more than 6 months of experience. She likes to keep up with the trending technologies. She is familiar with languages such as C,C++,Java,Scala and is currentky working on akka,akka http and scala. Her hobbies include watching tv series and movies, reading novels and dancing.

1 thought on “How to use extractors in Scala ?

Leave a Reply

%d bloggers like this: