Scala Foundation Course - Scala Match Case


Welcome back. The next item in the Scala control abstraction is the Match Case expression. Match case is the foundation for the pattern matching in Scala. In this session, I will introduce you to the syntactical structure and the most basic usage of Match Case. I will cover pattern matching in a separate class.
At the most basic level, Scala's Match Case is just like a switch statement in Java or C++. So, like any other language, the Match Case allows you to select among multiple alternatives. Here is an example.

There are few important observations and differences from the other languages.

  1. The underscore is the placeholder that matches everything. So, it works as a default case. It must be the last case. If you try to place it somewhere else, I mean before any other Case, Scala compiler will throw an error.
  2. Another important observation is the absence of a break statement. Scala doesn't have any break statement. The break is implicit, and Scala will never fall through one alternative to the next.

You can also have multiple expressions for a case. Here is an example.


Look at the code for case one and case two. Do you see a difference? Case two doesn't have curly braces. So, curly braces in the case statement are optional. You can leave it safely.
Finally, the most important point. Like any other expression in Scala, the Match Case expression returns a value. So, here is the updated version.

If x matches to one, return "Case One" string. If x matches to two, return "Case Two" string. We don't use return keyword, but it returns a value.
Just like an If expression, you can use the Match Case anywhere in your code. Here is an example.

Great! You have seen the most basic form of Match Case expression. However, it is more flexible than just matching numbers and strings. We will come back to this topic once again in a separate video for pattern matching.
In the next video, I will talk about the while loops.



You will also like: