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

 

 

 

 

 

 

 

 

SCALA COLLECTIONS

SCALA COLLECTIONS :

List :

Scala Lists are similar to Arrays which means that all elements of a list have the same type but there are two important differences. First Lists are immutable (Cannot be changed) and Second Lists are represented Linked List.

scala > val names : List [String] = List (“Sreekanth”, “Vijay”, “Vinay”);

names : List[String] = List (Sreekanth, Vijay, Vinay)

scala > val names : List[String] = List (“Alien”, “Bob”, “Carey”);

names: List [String] = List (Alien, Bob, Carey)

scala > println(names (0));

O/P : Alien

scala > println (names (1));

O/P : Bob

scala > val marks = List[Int] = List [10,20,30,40)

marks: List[Int] = List(10,20,30,40)

scala > prinltn(marks. head)

O/P : 10

scala > prinltn (marks. tail)

O/P : 20,30,40

To Concatenate the Two Lists using :::

val names  = “Sreekanth” :: ( “Vijay”:: “Vinay”);

names : List [String] = List (Sreekanth, Vijay, Vinay)

val address = “Hyd” :: (“Banglore” :: (“Chennai” ))

address: List[String] = List (Hyd, Banglore, Chennai)

var name_address= names ::: address

name_address : List [String] = List (Sreekanth, Vijay, Vinay, Hyd, Banglore, Chennai)

Set :

Set is a collection that contains no duplicate elements. There are two kinds of Sets, the immutable and mutable. The difference between mutable and immutable objects that when an object is immutable the object itself can’t be changed.

By default Scala uses the immutable set.

Scala > val ranks = List (1,2,3,4,2,2,3,2)

ranks: List[Int] = List (1,2,3,4,2,2,3,2)

Scala > val ranks = Set(1,2,3,4,2,2,3,2)

ranks : scala .collection.immutable.Set[Int] = Set (1,2,3,4)

Set Operations in Scala:

Example : object setOperations

{

def main (args: Array[String])

{

val marks = Set(10,20,30,40);

val updateMarks = set(15,25,35,45);

println (“Max marks : ” + marks .max);

prinltn( “Min marks :” + marks.min);

prinltn (“marks.intersect(updateMarks): ” + marks.intersect(updateMarks));

}

}

 

 Maps:

  1. Scala map is a collection of key  and value pairs in a collection set.
  2. Any value can be retrieved based on its key.
  3. Keys are unique in the Map, but values need not be unique.
  4. There are two kinds of Maps, the immutable and the mutable.

scala > mapPrgogram.scala

object mapPrg

{

def main(args: Array[String])

{

val Technology= Map (“Java” -> “OOPS”, “ML” -> AI , “Hadoop” -> “Big Data”);

println(“Keys in Technologies:” + Technology.keys);

prinltn(“Values of Technologies:” + Technology.values)

}

}

scala > scalac mapProgram.scala

scala > scala mapProgram

Output:

Keys in Technologies: Set(Java, ML, Hadoop)

Values in Technologies : Map ( OOPS, AI, Big Data )

 

 

 

 

 

 

 

 

 

 

SCALA Iterators & Arrays With Examples

SCALA ITERATORS:

Scala iterator is not a collection, but rather a way to access the element of a collection one by one.

Here two basic operations on iterators

1.next

2. hasNext

A Call to it.next() will return the element of the iterator and advance the state of the iterator.

A Call to it.hasNext() will return more elements of the iterator

Example:

scala > val itObject = Iterator (“Hadoop”, “Scala”, “Spark”);

itObject: Iterator[String] = non – empty iterator

scala > while (itObject.hasNext) {

println(” ” + itObject.next())}

Hadoop

Scala  Spark

scala > println (“Size of Iterator : ” +itObject. size)

Size of Iterator : 3



SCALA ARRAYS:

Scala array is a normal array. To create an array of integers below like this:

scala > var arrayEle = Array (1,2,3,4,5,6,7,8) ;

arrayEle: Array[Int] = Array (1,2,3,4,5,6,7,8)

scala > for (x < – arrayEle) {

println(“Array elements”+ x)}

scala > println (arrayEle. length)

O/p : 8

 

 

 

SCALA LOOPS With Examples

SCALA LOOPS :

For Loop:

A for loop is repetition control structure that allows   to efficiently write a loop that needs to execute a specific number of times.

Different types of for loop in SCALA:

  1. For Loop with Collections
  2. For Loop with Range
  3. For Loop with Filters
  4. For Loop with Yield.

For Loop with Collections: 

for (var <- List)

{

statement(y);

}

Here the List variable is a collection type having a list of elements and for loop iterate through all the elements returning one element in x variable at a time.

Example:

object ForLoopCollections{

def main (args: Array[String])

{

var x=0;

val numList = List(1,2,3,4,5);

for (x <-numList)

{

println(“Value of X:” +x)

}

}

}

For Loop with Range:

for (var x <- Range)

{

statement(y);

}

Here Range is the number of numbers that represented as I to J and   ” <-” is means that “Generator” command as this operator only generating individual values from range of numbers.

Example:

object ForLoopRange{

def main(args: Array[String])

{

var x = 0;

for (x <- 1 to 100)

{

println(“Value of X:” + x);

}

}

}

For Loop with Filters:

for ( var x <- List if conditions 1; if conditions 2; if conditions 3…)

{

statement(y);

}

}

Example:

object ForLoopFilterDemo{

def main(args: Array[String])

{

var x =0;

val numList = List (1,2,3,4,5,6,7,8,9);

for ( x <- numList if x!=5; if x < 9)

{

println(“Value of X:”+x);

}

}

}

 

For Loop with Yield:

val NorVal = for { var x <- List if condition 1; if condition 2….}

yield x

Here to store return values from a for loop in a variable  or can return through a function.

Example:

object ForLoopYieldDemo{

def main(args: Array[String])

{

var x=0;

val numList = List(1,2,3,4,5,6,7,8,9);

val NorVal = for { x <- numList if x!=3; if x <9) yield a

for (x <- NorVal)

{

println(“Value of X”+x);

}

}

}

While Loop

Normally while loop statement repeatedly executes a target statement as long as a given condition is true.

while(condition)

{

statement(y);

}

Example:

object WhileLoopDemo{

def main(args: Array[String])

{

var x = 100;

while (x <300){

println (“Value of X:” +x);

x= x+1;

}

}

}

Do While Loop

Unlike while loop, which tests the loop condition at the top of the loop, the do while loop checks its condition at the bottom of the loop.

While and Do While loop is similar, except that a do while loop is guaranteed to execute at least one time.

Do

{

statement(y);

} while(condition);

Example:

object DoWhileLoopDemo{

def main(args: Array[String]{

var x =100;

do{

println (“Value of X :”+x);

x=x+1;

}while (x >300)

}

}

 

 

FUNCTIONS IN SCALA

Functions in SCALA:

1. Higher Order Functions in Scala:

I) foreach ()

II) map ()

III) reduce ()

I) foreach() :

scala > val technologies = List ( “Hadoop”, “Java”, “Salesforce”);

technologies: List[String] = List (Hadoop, Java, Salesforce)

scala >  technologies . foreach ((t:String) = > ( println (t) ) );

output:

Hadoop

Java

Salesforce

II) map() :

scala > val technologies = List ( “Hadoop”, “Java”, “Salesforce”);

technologies: List[String] = List (Hadoop, Java, Salesforce)

scala >  val tSize = technologies . map ((c) = > ( c.size));

tSize : List [Int] = List (6, 4, 10)

scala > println (tSize);

List (6,4,10)

III) reduce() :

scala > val score = List (183,186,190,191)

score: List [Int] = List (183,186,190,191)

scala > val totalScore = score.reduce( (a : Int, b: Int) = > (a+b));

totalMarks: Int = 750

scala> val totalScore =score. reduce((a,b) => (a+b));

totalMarks: Int = 750





Anonymous Functions in SCALA:

Anonymous Functions mainly the combination of Function literals and Function Values.

Function literals : Anonymous functions in source code is called function literals 

Function Values : Function literals are instantiated into objects are called function values.

Example of Anonymous Function:

Anonymous_Funct.scala

object Anonymous_Funct

{

def main (args: Array[String])

{

var add = (x: Int) => x+1;

var mul = (a:Int, b:Int) => a*b;

println (“Addition value :” + add(10));

println (“Multiple value : “+ mul (9, 10) );

println ( ” New Addition Value: ” + ( (10) – 5));

println ( ” New Multiplied Value: ” + ( mul  (10,9)+50 ) ) );

}

}

Output:

Scala> scalac Anonymous_Funct.scala

Scala> Anonymous_Funct

Addition value 11

Multiple value 19

New Addition Value 5

New Multiplied Value 140