How to use switch/case (simple pattern matching) in Scala?
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.
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
}
The following code works fine for me: it produces 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?