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

Rus*_*ott 11 enumeration scala

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

  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
Run Code Online (Sandbox Code Playgroud)

这是怎么回事?谢谢.

rse*_*nna 20

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

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

scala> x match { case EnumType.a => "a" case EnumType.b => "b" }
res2: String = b
Run Code Online (Sandbox Code Playgroud)


Kev*_*ght 8

ab在你的match块是不一样的枚举值a以及b,模式匹配器将简单地匹配x在第一种情况下,并将其绑定到一个新的值a(第二种情况将被忽略)

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

1)用反引号包装值:

x match {
  case `a` => "a"
  case `b` => "b"
}     
Run Code Online (Sandbox Code Playgroud)

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"
}   
Run Code Online (Sandbox Code Playgroud)

鉴于这些值(以所有意图为目的)常量,使用大写是更常见/惯用的解决方案.

请注意,只有首字母必须是大写字母,而不是整个文字的名称.

  • 请随意接受最让您震惊的任何内容:)顺便说一句,如果出现您认为更适合该问题的其他内容,您可以随时更改已接受的答案。 (2认同)