
120
CHAPTER 5
■ PATTERN MATCHING
The same code in Scala is shorter, and there’s no explicit casting.
def test2(in: Any) = in match {
case s: String => "String, length "+s.length
case i: Int if i > 0 => "Natural Int"
case i: Int => "Another Int"
case a: AnyRef => a.getClass.getName
case _ => "null"
}
The first line tests for a String. If it is a String, the parameter is cast into a String and
assigned to the
s variable, and the expression on the right of the => is returned. Note that
if the parameter is
null, it will not match any pattern that compares to a type. On the next
line, the parameter is tested as an
Int. If it is an Int, the parameter is cast to an Int, assigned
to
i, and the guard is tested. If the Int is a natural number (greater than zero), “Natural
Int” will be returned. In this way, Scala pattern matching replaces Java’s test/cast paradigm.
I find that it’s very, very rare that I do explicit testing and casting in Scala.
Case Classes
We saw case classes earlier in the book. They are classes that get toString, hashCode, and
equals methods automatically. It turns out that they also get properties and extractors.
Case classes also have properties and can be constructed without using
new.
Let’s define a case class:
case class Person(name: String, age: Int, valid: Boolean)
Let’s create an instance of one:
scala> val p = Person("David", 45, true)
p: Person = Person(David,45,true)
You may use new to create a person as well:
scala> val m = new Person("Martin", 44, true)
m: Person = Person(Martin,44,true)
19897ch05.fm Page 120 Wednesday, April 8, 2009 2:03 PM