Understanding Scala Extractors: apply and unapply with Examples
This article explains Scala extractors, showing how the apply and unapply methods work, provides code examples for email address extraction, and demonstrates their use in pattern‑matching scenarios.
An extractor is an object that extracts the parameters used to construct a given object.
The Scala standard library includes several predefined extractors, which we will briefly review.
In Scala an extractor is an object that defines an unapply method; unapply is the inverse of apply: it receives an object and returns the values that were used to build it.
The following example demonstrates an extractor for e‑mail addresses:
object Test {
def main(args: Array[String]) {
println ("Apply 方法 : " + apply("Zara", "gmail.com"));
println ("Unapply 方法 : " + unapply("[email protected]"));
println ("Unapply 方法 : " + unapply("Zara Ali"));
}
// optional constructor method
def apply(user: String, domain: String) = {
user + "@" + domain
}
// mandatory extractor method
def unapply(str: String): Option[(String, String)] = {
val parts = str split "@"
if (parts.length == 2){
Some(parts(0), parts(1))
} else {
None
}
}
}Running the code produces:
$ scalac Test.scala
$ scala Test
Apply 方法 : [email protected]
Unapply 方法 : Some((Zara,gmail.com))
Unapply 方法 : NoneThe object defines two methods, apply and unapply. Using apply you can create an instance without the new keyword, e.g., Test("Zara", "gmail.com") yields the string "[email protected]".
The unapply method performs the reverse operation: it receives an object and extracts the values that were used to construct it. In the example it extracts the user name and domain from an e‑mail address.
If the input string is not a valid e‑mail address, unapply returns None:
unapply("[email protected]") equals Some("Zara", "gmail.com")
unapply("Zara Ali") equals NoneExtractor usage with pattern matching
When a class is instantiated, the compiler calls the apply method; you can define apply in both classes and companion objects.
Similarly, unapply is used in match statements; the compiler automatically invokes it:
object Test {
def main(args: Array[String]) {
val x = Test(5)
println(x)
x match {
case Test(num) => println(x + " 是 " + num + " 的两倍!")
// unapply is called here
case _ => println("无法计算")
}
}
def apply(x: Int) = x * 2
def unapply(z: Int): Option[Int] = if (z % 2 == 0) Some(z / 2) else None
}Executing this code prints:
$ scalac Test.scala
$ scala Test
10
10 是 5 的两倍!Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Big Data Technology & Architecture
Wang Zhiwu, a big data expert, dedicated to sharing big data technology.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
