The Artima Developer Community
Sponsored Link

Java Community News
Daniel Spiewak Explains Scala Pattern Matching

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Frank Sommers

Posts: 2642
Nickname: fsommers
Registered: Jan, 2002

Daniel Spiewak Explains Scala Pattern Matching Posted: Jan 30, 2008 4:54 PM
Reply to this message Reply
Summary
Daniel Spiewak started an article series devoted to Scala and aimed at Java programmers interested in learning the Scala language. Spiewak's latest article explains pattern matching and exception handling in Scala.
Advertisement

On the surface, Scala shares many similarities with Java, making it easy for experienced Java developers to start learning this new language. At a deeper level, however, Scala offers many concepts that are not present in Java, and the use of which can lead to more concise code, and hence make a developer more productive.

One such feature is pattern matching. In a series of articles aimed at Java developers learning Scala, Scala for Java Refugees Part 4: Pattern Matching and Exceptions, Daniel Spiewak explains what pattern matching is, and how it helps simplify exception handling in Scala:

Scala exceptions are fairly intuitive beasts. They behave almost exactly like Java’s (with the exception of being all unchecked), providing a familiarity and an interoperability with existing Java libraries. The exception handling mechanism however demonstrates considerably more power, making use of Scala’s built-in pattern matching capabilities and thus maintaining a far more internally consistent syntax.

Spiewak introduces pattern matching by comparing it to the familiar Java case statement:

One of the major limitations of switch/case in Java (and really any C derivative language) is that it can only be used on primitives. You can’t use switch/case to test a String, for example (a need which arises more often than one would think). In fact, the most complex type testable within switch/case is the Enum, and even this is just being reduced to its ordinal values under the surface. In short, switch/case is a very crippled hold-over from the dark ages of #include and extern...

For example, Scala’s match statements are not restricted to “primitive” types (which Scala doesn’t have, incidentally). You can just as easily perform pattern matching on strings or even more complex values... Not only is Scala capable of inspecting the type it is matching, but also values within that type.

For example, the instanceof operation in Scala looks like this:

var obj = performOperation()
var cast:Color = obj match {
  case x:Color => x
  case _ => null
}

[In this example,] we’re actually performing pattern matching against the type of the input. If the type matches, then the case-local variable x is populated with the value from obj and assigned type Color. This variable can then be returned from the match, and thus assigned to cast. If no type is matched, just return null.

Spiewak then explains how pattern matching can simplify exception handling in Scala:

The only real difference between Scala’s exception dispatch and Java’s is that Scala does not have checked exceptions... Scala does not force you to catch exceptions, it trusts that you’ll clue in when your program crashes...

Spiewak first introduces an example that checks the range of an input value, and throws an exception if the input is outside that range. The exceptions are pattern-matched in the client code:

def checkPrime(n:Int) = {
  if (n < 1 || n > 10) {
    throw new IllegalArgumentException("Only values between 1 and 10")
  }
 
  n match {
    case 1 => true
    case 2 => true
    // ...
  }
}

So how do we invoke this method, pedantically watching for exceptions? It turns out that the syntax looks surprisingly like pattern matching:

try { checkPrime(12) } catch { case e:IllegalArgumentException => e.printStackTrace() }

If we wanted to catch all exception types, we could resort to ... the underscore:

try {
  checkPrime(12)
} catch {
  case e:_ => e.printStackTrace()
}

What do you think of Scala's pattern matching?

Topic: Jeremy Zawodny on the Yahoo YUI Ajax CSS Grid Builder Previous Topic   Next Topic Topic: Clustering Scala Actors with Terracotta

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use