The extractor extracts the parameters that construct the object from the object passed to it.
The Scala standard library contains some predefined extractors, which we will take a quick look at.
The Scala extractor is an object with a unapply method. The
unapply
method can be regarded as
apply
. The reverse operation of the
unapply
accept an object and then extract the value from the object, which is usually used to construct the value of the object.
The following example demonstrates the extractor object for an email address: Execute the above code, and the output is as follows: The above object defines two methods: The In the instance When we instantiate a class, we can take 0 or more arguments, and the compiler will call the As we mentioned before. Execute the above code, and the output is as follows: 8.41.1. Example #
object Test {
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 (Required)
def unapply(str: String): Option[(String, String)] = {
val parts = str split "@"
if (parts.length == 2){
Some(parts(0), parts(1))
}else{
None
}
}
}
$ scalac Test.scala
$ scala Test
Apply method : Zara@gmail.com
Unapply method : Some((Zara,gmail.com))
Unapply method : None
apply
and
unapply
method. Pass through
apply
method we do not need to use
new
. You can createan object by doing so. So you can construct a string “ Zara @ gmail . com ” by saying Test (“Zara”, “gmail.com”).
unapply
method can be regarded as the
apply
reverse operation of the
unapply
accept an object and then extract the value from the object, which is usually used to construct the value of the object. In the example, we use
Unapply
method to extract the suffix of the user name and e-mail address from the object.
unapply
method is returned when the passed string is not an email address
None
. The code is demonstrated as follows:unapply("Zara@gmail.com") equivalent to Some("Zara", "gmail.com")
unapply("Zara Ali") equivalent to None
Extractor uses pattern matching #
apply
method. We can define it in both classes and objects
apply
method.
unapply
used to extract the value we specified to find, which is similar to that of the
apply
operation is the opposite. When we use the
match
statement is
unapply
, which will be executed automatically, as follows: 8.41.2. Example #
object Test {
def main(args: Array[String]) {
val x = Test(5)
println(x)
x match
{
case Test(num) => println(X+"is"+num+" twice!")
//unapply Called
case \_ => println("incalculable")
}
}
def apply(x: Int) = x*2
def unapply(z: Int): Option[Int] = if (z%2==0) Some(z/2) else None
}
$ scalac Test.scala
$ scala Test
10
10 is twice as much as 5!