如何在 Scala 中使用 switch/case(简单模式匹配)? [英] How to use switch/case (simple pattern matching) in Scala?
问题描述
我发现自己陷入了一件非常微不足道的事情:-]
I've found myself stuck on a very trivial thing :-]
我有一个枚举:
object Eny extends Enumeration {
type Eny = Value
val FOO, BAR, WOOZLE, DOOZLE = Value
}
在代码中,我必须有条件地将其转换为数字(变量-数字对应因上下文而异).我写:
In a code I have to convert it conditionally to a number (varianr-number correspondence differs on context). I write:
val en = BAR
val num = en match {
case FOO => 4
case BAR => 5
case WOOZLE => 6
case DOOZLE => 7
}
这给了我每个分支的无法访问的代码"编译器错误,但无论是第一个(在这种情况下为case FOO => 4").我做错了什么?
And this gives me an "unreachable code" compiler error for every branch but whatever is the first ("case FOO => 4" in this case). What am I doing wrong?
推荐答案
我怀疑你实际使用的代码不是FOO
,而是foo
,小写,这将导致 Scala 只是将值分配给 foo
,而不是将值与其进行比较.
I suspect the code you are actually using is not FOO
, but foo
, lowercase, which will cause Scala to just assign the value to foo
, instead of comparing the value to it.
换句话说:
x match {
case A => // compare x to A, because of the uppercase
case b => // assign x to b
case `b` => // compare x to b, because of the backtick
}
这篇关于如何在 Scala 中使用 switch/case(简单模式匹配)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!