我想在这里实现的是将 astring
与 an 的值进行比较enum
,我尝试使用 if
object FooType extends Enumeration {
type FooType = Value
val FooA = Value("FA")
val FooB = Value("FB")
}
val x = "FA"
if (x == FooType.FooA) //Does not match
println("success using if without toString")
if (x == FooType.FooA.toString) //match
println("success using if with toString")
println(FooType.FooA) //will print into "FA"
Run Code Online (Sandbox Code Playgroud)
至少,当我将它与enum
withtoString
方法进行比较时,它仍然运行良好。但如果我把它改成 a match case
,它就会变成error
an
x match {
case FooType.FooA.toString => println("success using match")
}
ScalaFiddle.scala:19: error: stable identifier required, but ScalaFiddle.this.FooType.FooA.toString found.
case FooType.FooA.toString => println("success using match")
^
Run Code Online (Sandbox Code Playgroud)
有没有办法通过使用匹配大小写来实现这一点?
您必须将其转换String
为FooType
然后使用 match
object FooType extends Enumeration {
type FooType = Value
val FooA = Value("FA")
val FooB = Value("FB")
}
val x = FooType.withName("FA")
x match {
case FooType.FooA => println("matched")
case _ => println("did not match")
}
Run Code Online (Sandbox Code Playgroud)