×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Pattern Matching in Scala

By IncludeHelp Last updated : November 16, 2024

Scala Pattern Matching

Scala pattern matching is a commonly used feature which has huge support by Scala language. Pattern matching in Scala is the same as the switch in Java or another programming language.

Matching a pattern contains a sequence of alternative of the pattern to be considered. Each sequence is a case of the Scala pattern matching. For all alternatives, the case has expressions which are evaluated for matching pattern matches. The arrow symbol '=>' is used as a separator between the patterns and expressions.

The match Keyword

The match keyword is used to define a pattern matching block. This block contain cases that are that turns that if matched will execute a set of expressions (a block of code).

In Pattern matching, there must be at least one case (also called alternative) with sum values for which the input pattern can be matched. If no keyword is matched then the last catch-all(_) case is executed. The expression that is evaluated after the matches found is actually a block code that is needed to be Evaluated. For a pattern-matching function, any sort of data can be matched based on first match policy (for you cases matching, the first one is used).

Example of Pattern Matching

object Demo {

  def matchNo(number: Int): String = {
    number match {
      case 1 => "Hello"
      case 2 => "Welcome"
      case _ => "to Scala"
    }
  }

  def main(args: Array[String]): Unit = {
    println(matchNo(3))  // calling matchNo method with 3 as argument
  }
}

Output

to Scala

Code Explanation

The above code will print to Scala because number 3 is matched to the default value of the match pattern function. the function three values, matching cases 1,2 and default(_).

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.