Pattern Matching gives a very gentle introduction to Scala’s
match keyword is akin to Java’s
switch statement, however it is far more powerful.
Suppose you wish to examine a URL to determine, by extension, how to render an object you’ve looked up. So a url like
/people/dave.xml would find a person named “dave” and return the data as XML. Similarlyi,
/people/dave.json would return the data as JSON.
In Java, you would do something like this:
Now, you can certainly factor that horrible
if-then-else-if structure out, but it seems a shame to have to do that. Also, the null checking and temporary variables are a bit noisy. Here’s the same thing in Scala:
We are using two case statements here. In the first one, we combine the search for the
'.' character with the substring to get the extension. The result is an instance of Scala’s
Option class, which is better way of encapsulating “no value” than null is.
Essentially what this statement means is “if the rest of
lastIndexOf was -1, set
None (no value), otherwise, set it to the substring following the
case section decides which rendering to use. This is a bit easier to grok, as it’s basically a compact
if-then-else-if construct. The thing to note here is that the expression
Some("xml") means "if our
extension (which is an instance of
String) is not
None and it’s string is “xml”, we match. This much more compact (and readable) than
if ( (ext != null) && (ext.equals("xml") ) from the Java code.
Finally, note that the expression
case _ is akin to
default in a Java
This just touches the surface of Scala’s pattern matching.
Suppose you wish to add rendering of your object’s encoding after the
handleOutput call. Suppose that you wish to handle anything, not just instances of
Entity, and you also wish to hide the names of any
Person (a subclass of
Entity) who is under 18 years old.
Note that we aren’t just switching based on the value of
obj, but also on it’s type, and it’s contents; the guard condition in the first
case statement allows us to refine our match. Anyone under 18 will match this; anyone else who is a
Person will match the second
case, with any other
Entity instance matching the third. Finally, we just
Entity objects that we receive.
My Thoughts on this Feature
I almost never use
switch statements in Java, because they are essentially useless. Even if all it did here is get rid of annoying
if-then-else blocks, I’d call it a win. As it stands, this is one of the coolest features of Scala and a really cool thing to have that takes advantage of the type information we get via static typing.
Last Updated 09/17/2009 at 10:49:32 AM by davecblog comments powered by Disqus
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.