Pattern Matching in Scala

Pattern Matching in Scala with Examples





A pattern match includes a sequence of alternatives each starting with the keyword use case. Each alternative includes a pattern and one or more expressions.

Example :

object PatternDemo {

def main(args : Array[String])

{

var months = List(“Jan”,”Feb”,”Mar”,”Apr”,”May”)

for (month <- months)

{

prinltn (month)

month match{

case “Jan” => prinltn (“First Month of the Year”)

case “Feb” => prinltn (“Second Month of the Year”)

case “Mar” => prinltn (“Third Month of the Year”)

case “Apr” => prinltn (“Fourth Month of the Year”)

case “May” => prinltn (“Fifth Month of the Year”)

}

}

Output:

Jan First Month of the Year

Feb Second Month of the Year

Mar Second Month of the Year

Apr Second Month of the Year

May Second Month of the Year

Example 2:

object techPatternMatch

{

def main( args: Array[String] )

{

var technologies = List (“Java”, “Python”, “Hadoop”, “Scala” )

for (tech <- technologies ){

println (tech)

tech match{

case “Hadoop”  | “Spark”=> println (“Big data technlogies”)

case “Java”  | “C++”=> println (“OOPS”)

case “Python”  | “Go”=> println (“Advanced Tech”)

case “Scala” => println (“Functional Programming”)

}

}

}

Output:

Hadoop Big data technologies

Spark Big data technologies

Java OOPS

C++  OOPS

Python Advanced Tech

Go Advanced Tech

Scala Functional Programming

 

object letterMatch_Case

{

def main(args: Array[String]){

println (x)

x match() {

case x if x%2 == 0 => prinltn (“Number is Even”)

case x if x%2 == 1 => prinltn (“Number is Odd”)

}

}

Output:

1  Number is Odd

2 Number is Even