Tour of Scala
An extractor object is an object with an unapply
method. Whereas the apply
method is like a constructor which takes arguments and creates an object, the unapply
takes an object and tries to give back the arguments. This is most often used in pattern matching and partial functions.
import scala.util.Random
object CustomerID {
def apply(name: String) = s"$name--${Random.nextLong}"
def unapply(customerID: String): Option[String] = {
val stringArray: Array[String] = customerID.split("--")
if (stringArray.tail.nonEmpty) Some(stringArray.head) else None
}
}
val customer1ID = CustomerID("Sukyoung") // Sukyoung--23098234908
customer1ID match {
case CustomerID(name) => println(name) // prints Sukyoung
case _ => println("Could not extract a CustomerID")
}
Sukyoung
import scala.util.Random defined object CustomerID customer1ID: String = "Sukyoung---5392557361748469708"
The apply
method creates a CustomerID
string from a name
. The unapply
does the inverse to get the name
back. When we call CustomerID("Sukyoung")
, this is shorthand syntax for calling CustomerID.apply("Sukyoung")
. When we call case CustomerID(name) => println(name)
, we're calling the unapply method.
Since a value definition can use a pattern to introduce a new variable, an extractor can be used to initialize the variable, where the unapply method supplies the value.
val customer2ID = CustomerID("Nico")
val CustomerID(name) = customer2ID
println(name) // prints Nico
Nico
customer2ID: String = "Nico---4359663507340171480" name: String = "Nico"
This is equivalent to val name = CustomerID.unapply(customer2ID).get
.
val CustomerID(name2) = "--asdfasdfasdf"
name2: String = ""
If there is no match, a scala.MatchError
is thrown:
val CustomerID(name3) = "-asdfasdfasdf"
scala.MatchError: -asdfasdfasdf (of class java.lang.String) ammonite.$sess.cmd3$Helper.<init>(cmd3.sc:1) ammonite.$sess.cmd3$.<init>(cmd3.sc:7) ammonite.$sess.cmd3$.<clinit>(cmd3.sc:-1)
The return type of an unapply
should be chosen as follows:
Boolean
. For instance case even()
.Option[T]
.T1,...,Tn
, group them in an optional tuple Option[(T1,...,Tn)]
.Sometimes, the number of values to extract isn't fixed and we would like to return an arbitrary number of values, depending on the input. For this use case, you can define extractors with an unapplySeq
method which returns an Option[Seq[T]]
. Common examples of these patterns include deconstructing a List
using case List(x, y, z) =>
and decomposing a String
using a regular expression Regex
, such as case r(name, remainingFields @ _*) =>
.
Tour of Scala