Scala – Pattern Matching

  • date 26th April, 2021 |
  • by Prwatech |
  • 0 Comments

Pattern Matching in Scala

 

A Pattern Matching is a method of checking the given group of tokens for the presence of the particular pattern. It is the most broadly utiliz feature in Scala. It is a procedure for checking a value against a pattern. the is like the switch statement of Java and C.

In scala, “match” keyword is utilized rather than switch statement. “match” is constantly characterized in Scala’s root class to make its accessibility and to the all objects.

use case 1:

Scala> import scala.util.Random

scala> val x: Int = Random.nextInt(1)

val x: Int = 0

scala> x match {

     case 0 => “zero”

        1case 1 => “one”

        case 2 => “two”

        2case _ => “other”

     }

use case 2:

scala> val x: Int = Random.nextInt(4)

val x: Int = 3

scala> x match {

     1case 0 => “Leonardo”

     case 1 => “Tom”

     2case 2 => “Christian”

     case 3 => “steve”

     4case 4 => “Mark”

     }

use case 3:

scala> val abc: Int = Random.nextInt(2)

val abc: Int = 1

scala> abc match {

     case 0 => “Leonardo”

      2case 1 => “Tom”

    case 2 => “Christian”

   4case 3 => “steve”

    case 4 => “Mark”

     }

Pattern Matching in Scala

0
0

Quick Support

image image