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?
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` =>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With