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.

Syntax:

The _match _expression consist of multiple parts:

  1. The value we’ll use to match the patterns is called a _candidate _
  2. The keyword match
  3. At least one _case clause _consisting of the _case _keyword, the pattern, an arrow symbol, and the code to be executed when the pattern matches
  4. A _default clause _when no other pattern has matched. The _default clause is recognizable because it consists of the underscore character () and is the last of the case clauses

Example:

Here is a simple example to illustrate those parts:

Is match Better Replacement for the Java switch Statements and if/else Statements?

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:

  • First, match is an expression in Scala, it always results in a value.
  • Second, match expressions can be used with any type. If you want to match on your own types, go right ahead!
  • Third, Scala’s alternative expressions never “fall through” into the next case. In Java, we must use explicit break statements to exit a switch at the end of each branch, or we will fall through to the next branch. This is annoying and error-prone.
  • Fourth, if none of the patterns match, an exception named MatchError is thrown. This means we always have to make sure that all cases are covered, even if it means adding a default case where there’s nothing to do.

Patterns in match Expressions

Wildcard Patterns

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.

Constant Patterns

A constant pattern matches only itself. Any literal may be used as a constant.

Here is an example to illustrate constant patterns.

Variable 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

Pattern Match Anything in Scala
1.40 GEEK