Evgeny Veretennikov Evgeny Veretennikov -3 years ago 100
Scala Question

Scala: why duplicate declaration is allowed inside pattern matching?

It seems that we are able to bind pattern to identifier

and then to declare one more
identifier immediately in the same scope. Why does this code work?

"123" match {
case x@"123" =>
// I expected compilation error here, but it actually works. Even var works
val x = "456"
x // "456"

Explaining with something like link to SLS would be especially appreciated.

Answer Source

I don't think there's a dedicated explanation of this situation in SLS, but looking at Pattern matching expressions part of spec, one can find the following wording:

A pattern matching expression

e match { case p_1 => b_1 … case p_n => b_n }

The scope of the pattern variables in p_i comprises the pattern's guard and the corresponding block b_i.

Which can be understood as the block b_i has its own scope, which is nested into the scope of pattern variables.

Now your variable x is bound in the pattern variable scope p_i, and then is redefined in the b_i scope. This gives us the situation of nested scopes, and the normal rules of name shadowing in the nested scope apply.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download