In Previous chapter we learned about SCALA STRING INTERPOLATION and today lets check out SCALA PATTERN MATCHING.

In SCALA Pattern Matching you would match a pattern with a value. Now the pattern can be a variety of things which we will see using examples one by one.

First lets understand the syntax on Pattern Matching

value match {
	case pattern1 => when matched do this 
	case pattern2 => when matched do this
	case _        => if nothing matches do this
}

Where ,
value is the candidate which we are trying to find a match
match is the keyword used
pattern1 is the pattern with which we are trying to match value
_ is the default clause when no other patterns match.This is not mandatory.

WHEN PATTERN IS A CONSTANT

Now this syntax doesn’t work on its own. First you need to create a function which excepts the value as a parameter and the body contains the pattern matching code.

In the below code we are matching the value with patterns which are constant (ex: 1,0).

scala> def numcheck(x:Int):String = x match {
     | case 1 => "You entered 1"
     | case 0 => "You entered 0"
     | case _ => "You entered neither 1 or 0"
     | }
numcheck: (x: Int)String

scala> numcheck(1)
res1: String = You entered 1

scala> numcheck(0)
res2: String = You entered 0

scala> numcheck(9)
res3: String = You entered neither 1 or 0

Also, when there is no matching pattern the default pattern is triggered ( _ ).

WHEN PATTERN IS A VARIABLE

Variable Pattern matches with any value, so it behaves just like default clause (_) , but there is a difference. Let me use the same function as i used above but this time instead of default clause i will use a variable.

scala> def numcheck(x:Int):String = x match {
     | case 1 => "You entered 1"
     | case 0 => "You entered 0"
     | case num => s"You entered $num please enter either 1 or 0"
     | }
numcheck: (x: Int)String

scala> numcheck(9)
res5: String = You entered 9 please enter either 1 or 0

As you can see, the last statement got triggered but this time we were able to use the value which was passed . Also do note that i used string interpolator s in the last case, you can learn more about various string interpolation here.

WHEN PATTERN IS A SEQUENCE

We can also match Scala Sequences like Array, Vector, List etc. Do note that if you want to match a single element you need to use ( _ ) remember that this is different from default clause. Also if you want to check multiple elements then you can use ( * ) wild card character.

This could be confusing so lets check it with an example.

scala> def sequence( seq:Any) = seq match{
     | case Array(_)      => "An array with only one element"
     | case List (_,_)    => "A List with only 2 elements"
     | case List(1,_,_)     => "A List with only 3 elements where the 1st element is 1"
     | case Array(8,9,_*) => "An array beginning with first 2 elements as 8 and 9 follwed by mutiple elements"
     | case _             => "Sequence could not be identified"
     | }
sequence: (seq: Any)String

scala> sequence( Array(1))
res3: String = An array with only one element

scala> sequence( List(6,7))
res4: String = A List with only 2 elements

scala> sequence( List(1,6,7))
res5: String = A List with only 3 elements where the 1st element is 1

scala> sequence( Array(8,9,1,6,7))
res6: String = An array beginning with first 2 elements as 8 and 9 follwed by mutiple elements

scala> sequence( List(0,2,3))
res7: String = Sequence could not be identified

WHEN PATTERN IS A TYPE

Using typed pattern matching you can identify the datatype of the parameter passed. Let me explain with an example

scala> def finddatatype( input: Any ) = input match{
     | case str : String  => s"Input is of Srting Datatype and value is $str"
     | case int : Integer => s"Input is of Integer Datatype and value is $int"
     | }
finddatatype: (input: Any)String

scala> finddatatype(1)
res9: String = Input is of Integer Datatype and value is 1

scala> finddatatype("smith")
res10: String = Input is of Srting Datatype and value is smith

PATTERN GUARDS

What if you want to check for some additional conditions even if the pattern is matching before it executes the code. In such cases we use Pattern Matching using if <boolean expression>

Lets say you want to find if number of elements in List is less than ‘maxvar’ variable. How you can do it.

scala> def listfunc(x:Any , maxvar: Int) = x match{
     | case list:List[Any] if (list.length < maxvar) => s"The input List has less than $maxvar elements"
     | case _                                        => s"The input List has more than $maxvar elements"
     | }
listfunc: (x: Any, maxvar: Int)String

scala> listfunc(List(1,2,3),5)
res0: String = The input List has less than 5 elements

scala> listfunc(List(1,2,3,4,5,6),5)
res1: String = The input List has more than 5 elements

In the next chapter we will learn about SCALA CLASS

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from UnderstandingBigData

Subscribe now to keep reading and get access to the full archive.

Continue reading