Scala Pattern Matching

Pattern matching is a feature of scala. It works same as switch case in other programming languages. It matches best case available in the pattern.

Let's see an example.


Scala Pattern Matching Example

In the above example, we have implemented a pattern matching.

Here, match using a variable named a. This variable matches with best available case and prints output. Underscore (_) is used in the last case for making it default case.

Output:

One

Match expression can return case value also. In next example, we are defining method having a match with cases for any type of data. Any is a class in scala which is a super class of all data types and deals with all type of data. Let's see an example.

Scala Pattern Matching Example2

Output:

Hello
Next TopicScala while loop




Contact US

Email:[email protected]

Scala Pattern Matching
10/30