2

Scala Pattern Matching | Have A Look On Basics

 2 years ago
source link: https://blog.knoldus.com/scala-pattern-matching-have-a-look-on-basics/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Reading Time: 3 minutes

Pattern matching is the process of checking whether a specific sequence of characters/tokens/data exists among the given data. In Scala Pattern Matching is one of the most powerful feature which is basically similar to the switch statements in C , C++ or JAVA.

Pattern Matching in Scala :

It is the mechanism of checking a value against pattern. It gives a way of checking the given sequence of tokens for the presence of a specific pattern. Here, we match expressions against a pattern.

we can use “pattern matching” for the same purpose as “java switch,” but you’re using functional tools in an imperative manner.

Types Of Pattern Matching In Scala :

WildCard Pattern :

As the name WildCard defines itself it is the type of pattern which can match against any case or any object. No matter whats the types and the value of the pattern , it allows to match all types of objects.

WildCard Pattern Matching Code

Variable Pattern :

This pattern matching is quite similar to the WildCard pattern , we can identifier of the Variable Pattern is that, we are allowed to bound the value of an object to the variable so that we can use the value wherever required.

Variable Pattern Code

Constant Pattern:

As the name suggests, matching against the Constant. This type of Pattern is used to match a pattern against a Constant.

Constant Pattern Code

Stable Pattern :

It is quite similar as constant pattern matching , here also pattern matching is done against the Constant but in Stable Pattern Matching the constant is declared somewhere else in program , as shown in below code.

Stable Pattern Code

Tuple Pattern:

Hence we understood how to do pattern matching but all the above types works only for single value or object. But if we have multiple object or values to match then we can use Tuple Pattern Matching

Code for Tuple Pattern

Reference

https://data-flair.training/blogs/scala-pattern-matching/ for further update please visit….

https://blog.knoldus.com/

Conclusion :

In this blog we learned about the basic pattern matching in Scala , And types of Pattern Matching.

Scala Future


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK