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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With