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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43400055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 09:10:54  来源:igfitidea点击:

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

scala

提问by user 923227

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:

我发现这是因为在任何情况下都不存在“SomeStringValue”:

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.

当我添加 else 案例时: _ 它运行正确,如下所示。

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?

问题:在 Scala 中,case 构造中总是应该有一个匹配值的原因是什么?

回答by Cyrille Corpet

The matchconstruct is an expression in itself.

match构建体是在本身的表达式。

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

假设,而不是println语句,你有整数,那么整个块将是一个类型的值Integer

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

Now, what value should countbe ? That's why the matchstatement must handle all possible cases.

现在,应该count是什么值?这就是为什么该match语句必须处理所有可能的情况。

In some cases (such as when pattern matching against a sealed traitor 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.

在某些情况下(例如当模式匹配 asealed trait或 时sealed abstract class),编译器将能够给你一个警告,但大多数时候,错误会在运行时抛出,所以你真的需要小心。