Previous

Next

Tour of Scala

# Extractor Objects¶

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.

In [1]:
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

Out[1]:
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.

In [2]:
val customer2ID = CustomerID("Nico")
val CustomerID(name) = customer2ID
println(name)  // prints Nico

Nico

Out[2]:
customer2ID: String = "Nico---4359663507340171480"
name: String = "Nico"

This is equivalent to val name = CustomerID.unapply(customer2ID).get.

In [3]:
val CustomerID(name2) = "--asdfasdfasdf"

Out[3]:
name2: String = ""

If there is no match, a scala.MatchError is thrown:

In [4]:
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:

• If it is just a test, return a Boolean. For instance case even().
• If it returns a single sub-value of type T, return an Option[T].
• If you want to return several sub-values 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 @ _*) =>.

Previous

Next

Tour of Scala