Search⌘ K
AI Features

Switch Statements in Scala

Explore how the Scala match statement acts as an advanced version of the traditional switch, eliminating the need for break or return keywords. Understand pattern matching using case classes, replacing instanceof checks, and see how catch blocks leverage match for exception handling. This lesson enhances your Scala programming skills with clear examples and applications of match syntax.

We'll cover the following...

Match is switch on steroids

You can use the match statement much like a switch statement. Check out the following code for an example of the syntax:

Scala
object Main {
def main(args: Array[String]) {
println(wordFor(1));
}
// method containing match keyword
def wordFor(number:Int) = number match {
case 1 => "one"
case 2 => "two"
case 3 => "three"
case _ => "unknown"
}
}

There’s no need for a return or break keyword because the match statement actually returns whatever value is returned from the matched case ...