I think that shadow variables are too dangerous to use them. Why does Scala support this language construct? There should be some strong reason for that, but I cant find it.
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…
I think that shadow variables are too dangerous to use them.
You are entitled to think whatever you want. However, since you have provided no data, studies or even reasons, that opinion has no value.
Why does Scala support this language construct?
Because it is useful. Programmers don't need to invent arbitrary identifier names just because some identifier in scope is already using it.
It makes wildcard imports more useful as well, as it removes the chance of a compile breaking just because a third party added a identifier you are using.
There should be some strong reason for that, but I cant find it.
Why should there be a strong reason for that? There are advantages to it, and in the absence of disadvantages (you presented none), that is enough.
EDIT
In answer to the disadvantages explained, I must say that is a special case of shadowing. Shadowing also affects everything in import, either through import
statements or through nested package
statements, and everything that is in the same package.
Let's see some examples:
// Not allowed, because it shadows List
import java.util._
class A {
// Not allowed, because it shadows this, hashCode, equals, toString
class B
}
That would make for a very annoying language.
© 2022 - 2024 — McMap. All rights reserved.