Home » Scala language

Pattern Matching in Scala

Scala pattern matching: pattern matching feature is check for the equivalence of an object with a string. In Scala pattern matching classes are strong. In this tutorial on Scala pattern matching, we will learn about pattern matching with sample code.
Submitted by Shivang Yadav, on July 25, 2019

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 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:

object Demo {
    
    def matchno(x: Int): String = x match {
        case 1 => "Hello"
        case 2 => "Welcome"
        case _ => "to Scala "
    }
    
    def main(args: Array[String]) {
        println(matchno(3))
    }  
}

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.