Desktop version

Home arrow Computer Science arrow Building Applications with Scala

Source

Advanced pattern matcher in Scala REPL

Following is an Advanced Pattern Matcher using Scala REPL:

$ scala

Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77). Type in expressions for evaluation. Or try :help. scala>def factorial(n:Int):Int = n match {

| case 0 => 1

| case n => n * factorial(n - 1)

| }

factorial: (n: Int)Int scala>

scala>println(factorial(3))

6

scala>println(factorial(6))

720

scala>

Pattern Matcher can be used in a very functional way. For instance, in the preceding code, we use the Pattern Matcher for recursion. There is no need to create a variable to store the result, we can put the Pattern Matcher straight to the function return, which is very convenient and saves lots of lines of code.

Advanced complex pattern matcher in Scala REPL

Following is an Advanced complex Pattern Matcher using Scala REPL:

$ scala

Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77). Type in expressions for evaluation. Or try :help. scala>trait Color defined trait Color

scala>case class Red(saturation: Int) extends Color defined class Red

scala>case class Green(saturation: Int) extends Color defined class Green

scala>case class Blue(saturation: Int) extends Color defined class Blue

Introduction to FP, Reactive, and Scala

scala>def matcher(arg:Any): String = arg match {

| case "Scala" => "A Awesome Language"

M

| case x: Int => "An Int with value

+ x

| case Red(100) => "Red sat 100"

| case Red(_) => "Any kind of RED sat"

| case Green(s) if s == 233 => "Green sat 233"

| case Green(s) => "Green sat " + s

| case c: Color => "Some Color: " + c

| case w: Any => "Whatever: " + w

| }

matcher: (arg: Any)String scala>println(matcher("Scala"))

A Awesome Language scala>println(matcher(1))

An Int with value 1

scala>println(matcher(Red(100)))

Red sat 100

scala>println(matcher(Red(160)))

Any kind of RED sat

scala>println(matcher(Green(160)))

Green sat 160

scala>println(matcher(Green(233)))

Green sat 233

scala>println(matcher(Blue(111)))

Some Color: Blue(111)

scala>println(matcher(false))

Whatever: false

scala>println(matcher(new Object))

Whatever: java.lang.Object@b56c222 scala>

The Scala Pattern Matcher is really amazing. We just used an if statement in the middle of the Pattern Matcher, and also _ to specify a match for any kind of red value. We also used case classes in the middle of the Pattern Matcher expressions.

 
Source
Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >

Related topics