如何在 Scala 中使用 switch/case(简单模式匹配)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3639150/
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
How to use switch/case (simple pattern matching) in Scala?
提问by Ivan
I've found myself stuck on a very trivial thing :-]
我发现自己陷入了一件非常微不足道的事情:-]
I've got an enum:
我有一个枚举:
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
}
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?
这给了我每个分支的“无法访问的代码”编译器错误,但不管第一个是什么(在这种情况下为“case FOO => 4”)。我究竟做错了什么?
回答by Daniel C. Sobral
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.
我怀疑您实际使用的代码不是小写FOO,而是foo小写,这将导致 Scala 仅将值分配给foo,而不是将值与其进行比较。
In other words:
换句话说:
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
}
回答by Matthew Farwell
The following code works fine for me: it produces 6
以下代码对我来说很好用:它产生 6
object Eny extends Enumeration {
type Eny = Value
val FOO, BAR, WOOZLE, DOOZLE = Value
}
import Eny._
class EnumTest {
def doit(en: Eny) = {
val num = en match {
case FOO => 4
case BAR => 5
case WOOZLE => 6
case DOOZLE => 7
}
num
}
}
object EnumTest {
def main(args: Array[String]) = {
println("" + new EnumTest().doit(WOOZLE))
}
}
Could you say how this differs from your problem please?
你能说这与你的问题有什么不同吗?

