Scala Pattern Matching
Scala provides a powerful pattern-matching mechanism, which is widely used.
A pattern match consists of a series of alternatives, each beginning with the keyword case. Each alternative contains a pattern and one or more expressions. The arrow symbol => separates the pattern from the expressions.
The following is a simple example of pattern matching on an integer value:
Example
object
Test
{
def
main
(
args
:
Array
[
String
]
)
{
println
(
matchTest
(
3
)
)
}
def
matchTest
(
x
:
Int
)
:
String
=
x
match
{
case
1
=>
"one"
case
2
=>
"two"
case
_
=>
"many"
}
}
The output of the code above is:
$ scalac Test.scala
$ scala Test
many
match corresponds to switch in Java, but is written after the selector expression. That is: selector match { alternatives }.
A match expression evaluates by trying each pattern in the order written; as soon as a matching case is found, the remaining cases are not tried.
Next let's look at pattern matching on different data types:
Example
object
Test
{
def
main
(
args
:
Array
[
String
]
)
{
println
(
matchTest
(
"two"
)
)
println
(
matchTest
(
"test"
)
)
println
(
matchTest
(
1
)
)
println
(
matchTest
(
6
)
)
}
def
matchTest
(
x
:
Any
)
:
Any
=
x
match
{
case
1
=>
"one"
case
"two"
=>
2
case
y
:
Int
=>
"scala.Int"
case
_
=>
"many"
}
}
The output of the code above is:
$ scalac Test.scala
$ scala Test
2
many
one
scala.Int
In the example, the first case corresponds to integer 1, the second to the string two, and the third to a type pattern that checks whether the passed value is an integer--using pattern matching is better than using isInstanceOf to check types. The fourth case is the default catch-all alternative, matched when no other case matches, similar to default in switch.
Using Case Classes
A class definition using the case keyword is a case class; case classes are special classes optimized for pattern matching.
The following is a simple example of a case class:
Example
object
Test
{
def
main
(
args
:
Array
[
String
]
)
{
val
alice
=
new
Person
(
"Alice"
,
25
)
val
bob
=
new
Person
(
"Bob"
,
32
)
val
charlie
=
new
Person
(
"Charlie"
,
32
)
for
(
person
<
- List
(
alice, bob, charlie
)
)
{
person
match
{
case
Person
(
"Alice"
,
25
)
=>
println
(
"Hi Alice!"
)
case
Person
(
"Bob"
,
32
)
=>
println
(
"Hi Bob!"
)
case
Person
(
name, age
)
=>
println
(
"Age: "
- age +
" year, name: "
- name +
"?"
)
}
}
}
// case class
case
class
Person
(
name
:
String, age
:
Int
)
}
The output of the code above is:
$ scalac Test.scala
$ scala Test
Hi Alice!
Hi Bob!
Age: 32 year, name: Charlie?
When a case class is declared, the following happen automatically:
- Each constructor parameter becomes a val unless explicitly declared as var, which is not recommended;
- An apply method is provided in the companion object, so objects can be constructed without the new keyword;
- An unapply method is provided so that pattern matching works;
- toString, equals, hashCode, and copy methods are generated unless explicitly provided.