Scala Extractor
An extractor extracts the arguments that constructed an object from the object passed to it.
The Scala standard library contains some predefined extractors, and we will take a brief look at them.
A Scala extractor is an object with an unapply method. The unapply method is the reverse of the apply method: unapply takes an object and extracts values from it, and the extracted values are usually the ones used to construct the object.
The following example demonstrates an extractor object for email addresses:
Example
def main(args: Array[String]) {
println ("Apply method : " + apply("Zara", "gmail.com"));
println ("Unapply method : " + unapply("Zara@gmail.com"));
println ("Unapply method : " + unapply("Zara Ali"));
}
// Injection method (optional)
def apply(user: String, domain: String) = {
user +"@"+ domain
}
// Extraction method (mandatory)
def unapply(str: String): Option[(String, String)] = {
val parts = str split "@"
if (parts.length == 2){
Some(parts(0), parts(1))
}else{
None
}
}
}
Executing the above code produces the following output:
$ scalac Test.scala $ scala Test Apply 方法 : Zara@gmail.com Unapply 方法 : Some((Zara,gmail.com)) Unapply 方法 : None
The above object defines two methods:applyandunapplyThe apply method. Through the apply method, we can create objects without using the new operator. So you can construct a string "Zara@gmail.com" with the statement Test("Zara", "gmail.com").
The unapply method is the reverse of the apply method: unapply takes an object and extracts values from it, and the extracted values are usually the ones used to construct the object. In the example, we use the unapply method to extract the username and the domain suffix of the email address from the object.
In the example, the unapply method returns None when the passed string is not an email address. The code is demonstrated as follows:
unapply("Zara@gmail.com") 相等于 Some("Zara", "gmail.com")
unapply("Zara Ali") 相等于 None
Extractors Use Pattern Matching
When we instantiate a class, we can pass zero or more parameters, and the compiler calls the apply method during instantiation. We can define the apply method in both the class and the object.
As we mentioned earlier, unapply is used to extract the values we specify to look for, and it is the opposite of apply. When we use a match statement in an extractor object, unapply is executed automatically, as shown below:
Example
def main(args: Array[String]) {
val x = Test(5)
println(x)
x match
{
case Test(num) => println(x + " is " + num + " twice! ")
// unapply is called
case _ => println("Cannot calculate")
}
}
def apply(x: Int) = x*2
def unapply(z: Int): Option[Int] = if (z%2==0) Some(z/2) else None
}
Executing the above code produces the following output:
$ scalac Test.scala $ scala Test 10 10 是 5 的两倍!Other Extensions