Why does Scala support shadow variables? [closed]

Just as a reminder: A variable, method, or type is said to shadow another variable, method, or type of the same name when it is declared in an inner scope, making it impossible to refer to the outer-scope entity in an unqualified way (or, sometimes, at all). Scala, just like Java, allows shadowing.

One possible reason I could see is that in Scala, it is frequent to have many nested scopes, each of which is relatively short (compared to e.g. Java or C++). Indeed, a block can start anywhere where an expression is expected, thus starting a new scope. The use of the shadowing names in the inner scopes is thus, on average, closer to their declaration and less ambiguous.

Moreover, inline closures often lead the programmer to need new variable names in a scope that is already crowded. Allowing shadowing also allows to keep using descriptive names that are sufficiently to the point, even if they are the same as al already used name, instead of inventing other weird names — like prefixing them with my, local, or (worse) _ or single-letter names…

Shadowing becomes less of a problem with good IDEs which can e.g. highlight in your source code the declaration of, and the references to, the variable under the cursor.

Just my two cents here…

Leave a Comment