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.
相关问题
- Unusual use of the new keyword
- Get Runtime Type picked by implicit evidence
- What's the point of nonfinal singleton objects
- PlayFramework: how to transform each element of a
- Error in Scala Compiler: java.lang.AssertionError:
相关文章
- Gatling拓展插件开发,check(bodyString.saveAs("key"))怎么实现
- RDF libraries for Scala [closed]
- Why is my Dispatching on Actors scaled down in Akk
- How do you run cucumber with Scala 2.11 and sbt 0.
- GRPC: make high-throughput client in Java/Scala
- Setting up multiple test folders in a SBT project
- Testing request with CSRF Token in Play framework
- Run project with java options via sbt
You are entitled to think whatever you want. However, since you have provided no data, studies or even reasons, that opinion has no value.
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.
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 nestedpackage
statements, and everything that is in the same package.Let's see some examples:
That would make for a very annoying language.
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…