Pattern Matcher

When you code in Java, you can use a Switch statement. However, in Scala, we have a more powerful feature called Pattern Matcher, which is a kind of switch but on steroids.

Simple Pattern Matcher in Scala

Following is a Simple Pattern Matcher in Scala:

$ 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 resolve(choice:Int):String = choice match {

| case 1 => "yes"

| case 0 => "no"

| case _ => throw new IllegalArgumentException("Valid arguments

are: 0 or 1. Your arg is:

" + choice)

| }

resolve: (choice: Int)String scala>println(resolve(0)) no

scala>println(resolve(1)) yes

scala>try {

| println(resolve(33))

| } catch{

| case e:Exception => println("Something Went Worng. EX: " + e)

| }

Something Went Worng. EX: java.lang.IllegalArgumentException: Valid

arguments are: 0 or 1. Your arg is: 33


Scala uses Pattern Matcher for error handling. Java does not have Pattern Matcher like Scala. It's similar to a switch statement; however, Pattern Matcher can be used in a method return statement as you can see in the preceding code. Scala developers can specify a special operator called _ (Underscore), which allows you to specify anything in the Pattern Matcher scope. This behavior is similar to else in an if conditional. However, in Scala, you can use _ in several places, and not only as the otherwise clause, like in Java switch.

Error handling in Scala is similar to error handling in Java. We use try... catch blocks. The main difference is that you have to use Pattern Matcher in Scala, which is great because it adds more flexibility to your code. Pattern Matcher in Scala can operate against many data structures like case classes, collections, integers, and strings.

The preceding code is pretty simple and straightforward. Next we will see a more complex and advanced code using the Scala Pattern Matcher feature.

< Prev   CONTENTS   Source   Next >