Scala 枚举类型在匹配/大小写中失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21412226/
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 06:01:59  来源:igfitidea点击:

Scala enumeration type fail in match/case

scalaenumeration

提问by RussAbbott

Enumerated values seem to fail in match/case expressions. This is what happens in a worksheet.

枚举值似乎在匹配/案例表达式中失败。这就是工作表中发生的情况。

  object EnumType extends Enumeration {
    type EnumType = Value
    val a, b = Value
  }

  import EnumType._
  val x: EnumType = b                //> x : ... .EnumType.EnumType = b

  x match {
    case a => "a"
    case b => "b"
  }                                  //> res0: String = a

  if (x == a) "a" else "b"           //> res1: String = b

What's going on? Thanks.

这是怎么回事?谢谢。

回答by rsenna

Like @Kevin Wright and @Lee just said, aand bwork as variable patterns, not as EnumTypevalues.

像@Kevin赖特和@Lee刚才说的,ab工作可变模式,而不是EnumType价值。

Another option to fix your code is making it explicit you are referencing values from the EnumTypesingleton:

修复您的代码的另一个选择是明确您正在引用来自EnumType单例的值:

scala> x match { case EnumType.a => "a" case EnumType.b => "b" }
res2: String = b

回答by Kevin Wright

The aand bin your matchblock aren't the same as the enumerated values aand b, the pattern matcher will simply match xin the first case and bind it to a new value a(the second case will be ignored)

您块中的aand与枚举值and 不同,模式匹配器将简单地匹配第一种情况并将其绑定到新值(第二种情况将被忽略)bmatchabxa

To avoid this, you have two choices:

为了避免这种情况,您有两个选择:

1) wrap the values in backticks:

1) 将值用反引号括起来:

x match {
  case `a` => "a"
  case `b` => "b"
}     

2) Make the enumerated values uppercase:

2) 使枚举值大写:

object EnumType extends Enumeration {
  type EnumType = Value
  val A, B = Value
}

import EnumType._
val x: EnumType = B

x match {
  case A => "a"
  case B => "b"
}   

Given that these values are (to all intents an purposes) constants, using uppercase is the more common/idiomatic solution.

鉴于这些值是(出于所有目的)常量,使用大写是更常见/惯用的解决方案。

Note that only the initial letter needs to be uppercase, not the name of the entire literal.

请注意,只有首字母需要大写,而不是整个文字的名称。

回答by Lee

ain your case statement is an unbound variable which matches anything. You need to explicitly check the value is equal to a:

a在您的 case 语句中,是一个匹配任何内容的未绑定变量。您需要明确检查该值是否等于a

x match {
    case v if v == a => "a"
    case _ => "b"
}