Evgeny Veretennikov
Evgeny Veretennikov

Reputation: 4249

Scala: why duplicate declaration is allowed inside pattern matching?

It seems that we are able to bind pattern to identifier x and then to declare one more x 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.

Upvotes: 2

Views: 97

Answers (1)

Haspemulator
Haspemulator

Reputation: 11318

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.

Upvotes: 4

Related Questions