Scala Match Expressions

Scala’s match is counterpart of Java’s switch

package com.scala.test

object TestMatch {

def checkMatch(i: Int): String = {
val str = i match {
case 1 => “One”;
case 2 => “Two”
case 3 => “Three”
case 4 => “Five”
case _ => “Did not Match”
}
return str
}

def main(args: Array[String]) {
for (a <- 1 to 5) {
println(checkMatch(a));
}
}

}

Output
One
Two
Three
Five
Did not Match

Difference between Scala’s match and Java’s switch

  1.  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.
  2. 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.
  3. One more difference from Java’s switch statements is that Scala match expressions can return a value.

Leave a Reply

Your email address will not be published. Required fields are marked *