Reputation: 11542
Ok, so this sounds like a trivial question.
val delim = ','
val chars = "abc,def".toCharArray
var i = 0
while (i < chars.length) {
chars(i) match {
case delim =>
println(s"($i): D!")
case c =>
println(s"($i): $c")
}
i += 1
}
I'm baffled that the output of this is:
(0): D!
(1): D!
(2): D!
(3): D!
(4): D!
(5): D!
(6): D!
I expected this:
(0): a
(1): b
(2): c
(3): D!
(4): d
(5): e
(6): f
How can I match on a Char value?
NOTE: If I hardwire the delim char "case ',' =>" instead, it works as expected! Why does it break if I use a Char-typed val?
Upvotes: 4
Views: 1584
Reputation: 51271
Your pattern match is creating a 2nd variable called delim
that shadows the 1st, and since a new and unadorned variable matches everything, that's the only case
that gets executed.
Use back-tics to tell the compiler to match against the existing variable, not a new one.
case `delim` =>
Upvotes: 9