如何在 Scala 中使用 switch/case(简单模式匹配)?
我发现自己陷入了一件非常琐碎的事情:-]
我有一个枚举:
object Eny extends Enumeration {
type Eny = Value
val FOO, BAR, WOOZLE, DOOZLE = Value
}
在代码中我必须有条件地将其转换为数字(varianr-number对应关系因上下文而异)。我写道:
val en = BAR
val num = en match {
case FOO => 4
case BAR => 5
case WOOZLE => 6
case DOOZLE => 7
}
这给了我每个分支一个“无法访问的代码”编译器错误,但无论第一个分支是什么(在本例中为“case FOO => 4”)。我做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我怀疑你实际使用的代码不是
FOO
,而是foo
,小写,这将导致Scala只将值分配给foo
,而不是将值与其进行比较。换句话说:
I suspect the code you are actually using is not
FOO
, butfoo
, lowercase, which will cause Scala to just assign the value tofoo
, instead of comparing the value to it.In other words:
下面的代码对我来说效果很好:它产生 6
你能说一下这与你的问题有什么不同吗?
The following code works fine for me: it produces 6
Could you say how this differs from your problem please?