CHAPTER 2 ■ SCALA SYNTAX, SCRIPTS, AND YOUR FIRST SCALA PROGRAMS
39
as the cases do not fall through to each other. This example matches the number against
a constant, but with a default:
44 match {
case 44 => true // if we match 44, the result is true
case _ => false // otherwise the result is false
}
Like C#, you can match against a String:
"David" match {
case "David" => 45 // the result is 45 if we match "David"
case "Elwood" => 77
case _ => 0
}
You can pattern match against case classes. Case classes provide a particularly good
set of pattern-matching semantics. In this case, we are matching against a
Stuff instance
with
name == David and age == 45 in a declarative form:
Stuff("David", 45) match {
case Stuff("David", 45) => true
case _ => false
}
We can test the name but accept any age:
Stuff("David", 45) match {
case Stuff("David", _) => "David"
case _ => "Other"
}
And we can extract the age field into the howOld variable:
Stuff("David", 45) match {
case Stuff("David", howOld) => "David, age: "+howOld
case _ => "Other"
}
We can place a guard between the pattern and the => that adds further testing that
cannot be described declaratively. In this case, we’ll extract the
age, and if it’s less than 30,
the result will be “young David”, otherwise the result will be “old David”:
Stuff("David", 45) match {
case Stuff("David", age) if age < 30 => "young David"
case Stuff("David", _) => "old David"
case _ => "Other"
}
19897ch02.fm Page 39 Wednesday, April 1, 2009 5:34 PM