Scala Extractors
An extractor extracts from an object passed to it the parameters that were used to construct that object.
The Scala standard library contains several predefined extractors, which we will briefly look at.
A Scala extractor is an object with an unapply method. The unapply method can be considered the reverse of the apply method: unapply takes an object and extracts values from it, which are usually the values used to construct that object.
The following example demonstrates an extractor object for email addresses:
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
}
}
}
The output of the code above is:
$ scalac Test.scala
$ scala Test
Apply 方法 : Zara@gmail.com
Unapply 方法 : Some((Zara,gmail.com))
Unapply 方法 : None
The above object defines two methods: apply and unapply methods. Through the apply method, we can create objects without using the new operation. So you can use the statement Test("Zara", "gmail.com") to construct the string "Zara@gmail.com".
The unapply method is the reverse of the apply method: unapply takes an object and extracts values from it, usually the values used to construct the object. In the example, we use the unapply method to extract the username and the email address suffix from the object.
In the example, the unapply method returns None when the passed string is not an email address. The code is demonstrated below:
unapply("Zara@gmail.com") 相等于 Some("Zara", "gmail.com")
unapply("Zara Ali") 相等于 None
Extractors and 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 classes and objects.
As we mentioned earlier, unapply is used to extract the values we specify to look for, and it performs the reverse operation of apply. When we use a match statement with an extractor object, unapply is executed automatically, as shown below:
Example
object
Test
{
def
main
(
args
:
Array
[
String
]
)
{
val
x
=
Test
(
5
)
println
(
x
)
x
match
{
case
Test
(
num
)
=>
println
(
x +
" is "
- num +
" twice as large!"
)
// unapply is called
case
_
=>
println
(
"Cannot compute"
)
}
}
def
apply
(
x
:
Int
)
=
x
2
def
unapply
(
z
:
Int
)
:
Option
[
Int
]
=
if
(
z
%
2
==
0
)
Some
(
z/
2
)
else
None
}
The output of the code above is:
$ scalac Test.scala
$ scala Test
10
10 是 5 的两倍!