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