Pattern Matching
Viewing old version e3c45fc73e3cd5f1b9bcba54b11b151248fab5aa; View Current
The Gist
Pattern Matching gives a very gentle introduction to Scala’s match and case keywords
My Interpretation
Scala’s match keyword is akin to Java’s switch statement, however it is far more powerful.
To get the flavor of the syntax, here’s how you might translate the only real values in computer programming into English:
Java could do this pretty easily, however Java is limited to primitive types and enumerations. In Scala, you can use pretty much anything. Suppose you wish to translate English words like “some”, “one” and “none” into UML-type quantifiers. In Java, you would need either an enumeration or a large if-then-else statement. In Scala, we can use match:
This, alone, is pretty useful. However, we can make this even more dynamic. Suppose we want our function to also translate numbers into exact amounts (e.g. approximate(34) yields 34) and we want to handle booleans, where a true is 1 and a false is 0..1. This would be some ugly Java code.
Scala’s match and case statements take care of all the casting. Yes, this is type safe code!
This construct is quite powerful. CaseClasses shows another way to use it to keep your code clean and clear.
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 08/22/2009 at 09:43:17 AM by davec
blog comments powered by Disqus
All Content by David Copeland is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.