Pattern matching is more like Java's switch
statements with a few differences. With one expression/value to match against several case statements, whenever a match happens, the corresponding block of code is executed. This gives more than one option for our program flow to follow. Java's switch is a fall-through statement, which means it executes all the statements after the very first match until it confronts a break
statement. In Scala, there's no break
statement. Also, there's no default case in Scala's pattern matching. Instead, a wildcard "_" is used that matches against any other case that has not been covered in previous case
statements.
Let's have a look at the syntactical difference between Java's switch and Scala's pattern matching statements:
The difference is obvious, as we already discussed. In Scala, we have to provide a case matching to our expression, otherwise the compiler will throw an error, MatchError
:
object PatternMatching extends App { def matchAgainst...