...

Cloud Computing - SCALA

Back to Course

Lesson Description


Lession - #694 SCALA PATTERN MATCHING


SCALA Patternmatch

Pattern matching is the second most broadly utilized element of Scala, after function values and closures. Scala offers incredible help for pattern matching, in processing the messages. An example match incorporates an arrangement of options, each beginning with thekeyword case. Every option incorporates an example and at least one expression, which will be evaluated on the off chance that the example matches. A bolt symbol => isolates the example from the expression. try the following model program, which tells the best way to match against a integer value.

Model
object Demo {
   def main(args: Array[String]>
{ println(matchTest(3>
>
} def matchTest(x: Int>
: String = x match { case 1 => "one" case 2 => "two" case _ => "many" } }

Save the above program in Demo.scala. The following commands are utilized to compile and execute this program.

command

\>scalac Demo.scala
\>scala Demo

Yield

many



Matching utilizing Case Classes
The case classes are unique classes that are utilized in pattern matching with case expression.syntactically, these are standard classes with a unique modifier: case.

try the following, it is a straightforward example matching model utilizing case class.

Model
object Demo {
   def main(args: Array[String]>
{ val alice = new Person("Alice", 25>
val bounce = new Person("Bob", 32>
val charlie = new Person("Charlie", 32>
for (individual <-List(alice, bounce, charlie>
>
{ individual match { case Person("Alice", 25>
=> println("Hi Alice!">
case Person("Bob", 32>
=> println("Hi Bob!">
case Person(name, age>
=> println( "Age: " + age + " year, name: " + name + "?">
} } } case class Person(name: String, age: Int>
}



Save the above program in Demo.scala. The following commands are utilized to compile and execute this program.
command

\>scalac Demo.scala
\>scala Demo

Yield

Greetings Alice!
Greetings Bob!
Age: long term, name: Charlie?