What you’ll learn in this blog post -
- Scala’s response to Java’s switch statement.
- Pattern Matching for Options.
- Exception Handling in Scala.
Switch statement is a common way in C/C++/Java to match a given variable and have different behaviors for different values. This is a sample syntax -
There are a couple of limitations in this -
Switch is a statement and not an expression. In the example above, we assign monthString to a value in every branch.
The Fall-Through Problem - You must explicitly have a break statement at the end of every branch, or you will fall through to the next branch.
Scala solves both the problems using Pattern Matching.
The same code above is simplified to the code below -
Guards enable you to add a condition to guard your default case. This makes the code much easier to read rather than nested switch statements or an if block within a switch branch in Java. Consider the example below -
Variables In Patterns
In Scala, you can also have a variable following a case keyword. This is used in a couple of scenarios -
- When you want to use the value of the variable in the branch.
- When you match for type. This is a preferred method when compared to isInstanceOf operator.
In Scala, pattern matching is also used to get the value of an Option type. This is done through the code below -
Exception Handling in Scala is a lot similar to Java. It also follows a similar syntax as the Pattern Matching.
Code. Learn. Explore