Labels

Tuesday, April 12, 2022

Match Expressions in Scala (Class -32)

 Scala has a concept of a match expression. This is also called “Pattern Matching”.

    Here, “match” keyword is used instead of switch statement. “Match” is always defined in Scala’s root class to make its availability to the all objects. This can contain a sequence of alternatives. Each alternative will start from case keyword. Each case statement includes a pattern and one or more expression which get evaluated if the specified pattern gets matched. To separate the pattern from the expressions, arrow symbol (=>) is used.





Pattern Matching include:

a)      For statement (with Yield & String)

b)      Arrays

FOR statement: Iteration over a particular row. Use both for mutability and immutability. We need to give println to give output.



For with Yield & String interpolation will give some return Output.


 In Real Time Projects, we use Map instead of For Yield.

An array is a linear data structure with a fixed number of elements. It is a collection that stores fixed number Arrays in Scala elements of the same datatype. In Scala, an array is 0 indexed, i.e. the first element has an index of zero. The last element of the array has an index of the last element minus one.

The Array keyword is used to create an array in Scala. There are multiple syntaxes to create an array.





An array can extend up to as many dimensions as you want but only 1-D2-D, and 3-D arrays are commonly used. 




Each match keyword must have at least one case clause. Each case statement returns a value, and the whole match statement is virtually a function that returns a matched value.

The match keyword is used to define a pattern matching block. This block contain cases that are that turns that if matched will execute a set of expressions (a block of code).


No comments:

Post a Comment