Wednesday, 19 August 2020

How to handle Scala.MatchError

 When no value matches to the match expression, Scala throws scala.MatchError.

Example

scala> var dayOfWeek = 10
var dayOfWeek: Int = 10

scala> var result = dayOfWeek match {
     |     case 1 => {"Monday"}
     |     case 2 => {"Tuesday"}
     |     case 3 => {"Wednesday"}
     |     case 4 => {"Thursday"}
     |     case 5 => {"Friday"}
     |     case 6 => {"Saturday"}
     |     case 7 => {"Sunday"}
     | }
scala.MatchError: 10 (of class java.lang.Integer)
  ... 32 elided

How to handle Scala.MatchError?

There are two ways to handle Scala.MatchError.

a.   Value Binding Patterns

b.   Wildcard Operator Patterns

 

Value Binding Patterns

In the value binding pattern, we use a variable that stores the value of the match variable.

 

For example, ‘someNumber’ is used to store the value of match variable.

 

var result = dayOfWeek match {

          case 1 => {"Monday"}

          case 2 => {"Tuesday"}

          case 3 => {"Wednesday"}

          case 4 => {"Thursday"}

          case 5 => {"Friday"}

          case 6 => {"Saturday"}

          case 7 => {"Sunday"}

          case someNumber => {

               println("Number is not in range of 1..7")

               "Not a valid input"

             }

         }

scala> var result = 10
var result: Int = 10

scala> var result = dayOfWeek match {
     |           case 1 => {"Monday"}
     |           case 2 => {"Tuesday"}
     |           case 3 => {"Wednesday"}
     |           case 4 => {"Thursday"}
     |           case 5 => {"Friday"}
     |           case 6 => {"Saturday"}
     |           case 7 => {"Sunday"}
     |           case someNumber => {
     |                println("Number is not in range of 1..7")
     |                "Not a valid input"
     |              }
     |          }
Number is not in range of 1..7
var result: String = Not a valid input

scala> print(result)
Not a valid input

Wild card Operator Pattern

_ is used to match anything.

 

Example

case _ => {……}

scala> var result = 10
var result: Int = 10

scala> 

scala> var result = dayOfWeek match {
     |           case 1 => {"Monday"}
     |           case 2 => {"Tuesday"}
     |           case 3 => {"Wednesday"}
     |           case 4 => {"Thursday"}
     |           case 5 => {"Friday"}
     |           case 6 => {"Saturday"}
     |           case 7 => {"Sunday"}
     |           case _ => {
     |                println("Number is not in range of 1..7")
     |                "Not a valid input"
     |              }
     |          }
Number is not in range of 1..7
var result: String = Not a valid input



Previous                                                    Next                                                    Home

No comments:

Post a Comment