hing allows for more concise and readable code while at the same time provide the ability to match elements against complex patterns.
In this blog, we will see the power of the Scala’s pattern matching in different use cases.
The _match _expression consist of multiple parts:
Here is a simple example to illustrate those parts:
match expressions can be seen as a generalization of switch statements and if/else statements. match expressions do everything that switch statements and if/else statements do, and much more.
However, there are few major differences to keep in mind:
The wildcard pattern ( _ ) matches any object whatsoever. It is used as a default case i.e., catch-all alternative. It can also be used to represent the element of an object whose value is not required.
Here is an example to illustrate wildcard patterns.
A constant pattern matches only itself. Any literal may be used as a constant.
Here is an example to illustrate constant patterns.
A variable pattern matches any object, just like a wildcard. But unlike a wildcard, Scala binds the variable to whatever the object is. So then, we can use this variable to act on the object further.
Also note that, in case clauses, a term that begins with a lowercase letter is assumed to be the name of a new variable that will hold an extracted value. To refer to a previously defined variable, enclose it in back-ticks. Conversely, a term that begins with an uppercase letter is assumed to be a type name.
To avoid duplication, case clauses also support an “or” construct, using a | method.
Here is an example to illustrate variable patterns.
#scala #tech blogs #pattern matching