Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using unicode variables in Scala tuple assignment

val ©® = 1
val (©, ®) = (1, 2)

Line 1 works fine in both Scalac and the REPL but line 2 chokes on both.

Is this a bug? Or is there a special syntax that I'm missing?

Disclaimer: I know that using non-ASCII variable names is a terrible idea. I came across this by complete accident. My codebase isn't full of wacky symbols, I swear. Please don't lynch me :)

like image 847
My other car is a cadr Avatar asked Mar 20 '23 22:03

My other car is a cadr


1 Answers

Maybe this helps:

scala> val (x, y) = (1, 2)
x: Int = 1
y: Int = 2

scala> val (X, Y) = (1, 2)
<console>:7: error: not found: value X
       val (X, Y) = (1, 2)
            ^
<console>:7: error: not found: value Y
       val (X, Y) = (1, 2)
               ^

What happens is that unicode is treated like uppercase characters when it comes to pattern matching, which means that, since it "starts" with an "uppercase letter", it thinks you are comparing to a constant instead of assigning values.

Another example:

val © = 1
val ® = 3

(1, 2) match {
  case (©, ®) => "Both match"
  case (_, ®) => "Second matches"
  case (©, _) => "First matches"
  case _      => "None match"
}

results in

res0: java.lang.String = First matches
like image 80
Daniel C. Sobral Avatar answered Mar 22 '23 19:03

Daniel C. Sobral