2. What is Extractors
●
An extractor in Scala is an object that has a method called
unapply as one of its members.
●
The purpose of that unapply method is to match a value
and take it apart.
●
The extractor object also defines a dual method apply for
building values, but this is not required.
●
Extractor is used to replace case classes patterns with
objects that hides the actual implementation of Branch
and Leaf.
3. ●
Extractors give you a way to create your own kinds of
patterns. You can write patterns without creating an
associated case class.
●
Extractors play a role similar to views in functional
programming languages
4. Ex:- A simple extractor for ScalaBook
scala> object ScalaBook {
– | def unapply(book:String):Option[String] =
– | if (book=="scala") Some("Scala") else None
– |}
– defined module ScalaBook
–
– scala> "scala" match {
– | case ScalaBook(f) => println (f+" is a great language !!!!!!")
– | case _ => println ("Bah")
– |}
– Scala is a great language !!!!!!
–
–
5. REPL
The same ScalaBook object from above can be used to
filter a list of Strings and only return Strings that contain
scala books :
scala> val scalabooks = List(“java” ,”scala” ,”php”)
foods: List[java.lang.String] = List(java,scala,php)
scala> for (ScalaBook(f) <- books) yield f
res29: List[String] = List(Scala)
6. Extractors versus case classes
●
Extractors break this link between data representations and
patterns while Case Classes expose the concrete
representation of data. This property is called
representation independence.
●
Using representation independence , we can change
implementation later without affecting client code .
●
Case classes are much easier to set up and to de-fine, and
they require less code.
●
If you need to expose a type to unknown clients, extractors
might be preferable because they maintain representation
independence.
7. Case classes usually lead to more efficient pattern
matches than extractors.
The Scala compiler can optimize patterns over case
classes much better than patterns over extractors. This is
because the mechanisms of case classes are fixed,
whereas an unapply or unapplySeq method in an extractor
could do almost anything.