Scala – Pattern Matching

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

Pattern Matching is a method of checking the given group of tokens for the presence of the particular pattern. It is the most broadly utilized feature in Scala. It is a procedure for checking a value against a pattern. It 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 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”

        case 1 => “one”

        case 2 => “two”

        case _ => “other”

     }

use case 2:

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

val x: Int = 3

scala> x match {

     case 0 => “Leonardo”

     case 1 => “Tom”

     case 2 => “Christian”

     case 3 => “steve”

     case 4 => “Mark”

     }

use case 3:

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

val abc: Int = 1

scala> abc match {

     | case 0 => “Leonardo”

     | case 1 => “Tom”

     | case 2 => “Christian”

     | case 3 => “steve”

     | case 4 => “Mark”

     }

 

0
0

Quick Support

image image