Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala.MatchError: <SomeStringvalue> (of class java.lang.String)

Tags:

scala

I was getting the error:

Exception in thread "main" scala.MatchError: SomeStringValue (of class java.lang.String)

I found that it was causing because of "SomeStringValue" was not present in any of the cases:

val test = "SomeStringValue"
test match {
  case "Name" => println("Name")
  case "Age"  => println("Age")
  case "Sex"  => println("Sex")
}

When I added the else case: _ it ran correctly as below.

val test = "SomeStringValue"
test match {
  case "Name" => println("Name")
  case "Age"  => println("Age")
  case "Sex"  => println("Sex")
  case _      => println("Nothing Matched!!")
}

Question: What is the reason that there should always be a matching value in the case construct in Scala?

like image 810
user 923227 Avatar asked Apr 13 '17 19:04

user 923227


1 Answers

The match construct is an expression in itself.

Suppose, instead of having println statements, you had integers, then the whole block would be a value of type Integer:

val test = "SomeStringValue"
val count: Int = test match {
  case "Name" => 1
  case "Age"  => 2
  case "Sex"  => 3
}

Now, what value should count be ? That's why the match statement must handle all possible cases.

In some cases (such as when pattern matching against a sealed trait or sealed abstract class), the compiler will be able to give you a warning, but most of the time, the error will be thrown at runtime, so you really need to be careful about it.

like image 169
Cyrille Corpet Avatar answered Oct 06 '22 00:10

Cyrille Corpet