Scala Match Expressions

Jakob Jenkov
Last update: 2014-05-25

Scala's match expressions can be used to select between a list of alternatives, just like multiple if-statements. Scala's match works similarly to Java's switch statements, although not exactly the same way. Here is a simple example:

var myVar = "theValue";

myVar match {
   case "someValue"   => println(myVar + " 1");
   case "thisValue"   => println(myVar + " 2");
   case "theValue"    => println(myVar + " 3");
   case "doubleValue" => println(myVar + " 4");
}

This match expression compares the value of the myVar variable with the values in each of the four case statements. If the value of myVar matches any of these values, the code following the matched case statement is executed.

What is different from Java is, that there is no break statement after each case, but the case statements do not "fall through", like they do in Java. In other words, in Java, if a value matches a case statement, all following case statements get executed too, until one of the case statements lists a break.

Another difference from Java's switch statement is, that Scala can match on other values than int's or long's. Scala can match on many other things. In the example above strings were used.

Match Expressions can Return a Value

One more difference from Java's switch statements is that Scala match expressions can return a value. Here is how:

var myVar = "theValue";

var myResult =
    myVar match {
       case "someValue"   => myVar + " A";
       case "thisValue"   => myVar + " B";
       case "theValue"    => myVar + " C";
       case "doubleValue" => myVar + " D";
    }
println(myResult);

Notice how the variable myResult is set equal to the value of the match expression. The match expression returns whatever value is assigned to it in the matching case statement. In this example the match expression will return myVar + " C".

Jakob Jenkov

Featured Videos

Java ConcurrentMap + ConcurrentHashMap

Java Generics

Java ForkJoinPool

P2P Networks Introduction

















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next