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:
- If it returns a single sub-value of type
T
, return aOption[T].
- If it is just a test, return a Boolean.
- If you want to return several sub-values
T1,...,Tn
, group them in an optional tupleOption[(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!
2 thoughts on “How to use extractors in Scala ?3 min read”
Comments are closed.