Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I match on a Char in Scala?

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?

like image 581
Greg Avatar asked Jan 02 '23 02:01

Greg


1 Answers

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` =>
like image 63
jwvh Avatar answered Jan 10 '23 16:01

jwvh