Scala has pattern matching... so what's the big deal? If you are a Java developer the power of pattern matching will probably be lost on you at first, but after you gain some experience with it a light will go on inside your head. And if you are a functional programmer, then you would expect Scala to have nothing less than excellent support for pattern matching since it is a new language that is partially a functional language. So what is pattern matching? I don't know a formal definition, but it does several things and I will give an example of each. But before we go any further, there are 2 concepts that work well with pattern matching (but are not required); tuples and case classes. Both of these topics have been explained in numerous other blog posts so I will just post very short summaries here, but familiarizing yourself with these topics will further your understanding of the power of pattern matching.
Many people like to think of pattern matching in this way.
Tuples
A tuple is a fixed size data structure that allows data to be of different types. Scala has a convenient syntax for tuples that looks like this:(1, 2.0, "three")Tuples are typically used instead of Lists or Arrays when the data types of the objects are not all the same.
Case Classes
In scala a case class is a special type of class (with some restrictions) that "exports its constructor parameters". So what does that mean? It means that you conveniently create and compare instances of the class. Pattern matching will even allow for some of the values to be compared and others to be set in one operation!case class Foo(firstData:Int, secondData:Int)
Pattern Matching
First, pattern matching is a glorified switch statement.
x match {
case 1 =>
println("x is 1")
case _ =>
println("x is not 1")
}
val x = Foo(3,5)
x match {
case Foo(z,5) =>
println(z)
case _ =>
println("we didn't have a match")
}
This says try to match the value of x and when you find a case that is true, execute the code block associated with that case. Don't forget that _ in Scala is like a wildcard character so it is like a set of all values except for the values from the previous case blocks because they were executed earlier. Scala's only advantage over Java here is that you can use objects and not just primitives or Enums for comparison.
Second, pattern matching is like built in assertions (well, sort of).
x match {
case 0 =>
println("x is 0")
case 1 =>
println("x is 1")
}
So in this contrived binary checker, we check x for a value that is either 0 or 1. So what would happen if x contained a value that was NOT 0 or 1? A scala.MatchError exception would be thrown! This allows for a clean form of defensive programming in that the developer does not have to handle all of the possible error conditions right here in the code. The developer can code the "sucess cases" and let exceptions be thrown for the exception cases and those exceptions can be handled by an error handling layer someone else in the code.
Third, pattern matching is useful for variable assignment
(assigning multiple variables on one line, assigning only certain variables, etc) This is where tuples enter the picture again.val a = (1,2.0,"three") val (d,e,f) = a println(d) println(e) println(f)This will produce the following results:
1 2.0 threeAdditionally, you could do:
val a = (1,2.0,"three") val (b,2.0,"three") = a println(b)This will print out 1 as expected. But NOTE that if the values in the second and third positions of the tuple did NOT match then an exception would have been thrown! So you could NOT do:
The following example would throw an exception!
val a = (1,2.0,"three") val (b,2.0,"3") = a println(b)
Many people like to think of pattern matching in this way.
- Do all of the bound variable values match?
- If yes, then we have a match!
- If not, what could the code do to make the statement true? (ie assign a value to an unbound variable...)
0 TrackBacks
Listed below are links to blogs that reference this entry: Scala Pattern Matching.
TrackBack URL for this entry: http://www.nearinfinity.com/mt/mt-tb.cgi/509



Leave a comment