简体   繁体   中英

In Scala, what is the reasoning behind allowing parameter shadowing?

This turns out to be completely acceptable to the compiler (at least in 2.10.3 and 2.11-M7):

def foo(n: Int) = {
  val n = 3
  n * 3
}

...this is probably because the parameter exists in the outer scope of the method/function body, which is the technical reasoning, but effectively, this can lead to problems (as I've just found out in real life code), so I'm wondering if this is just an unavoidable consequence of the language design, or if it actually serves a real (higher?) purpose.

PS it's even OK to use a different type for the shadowing name:

def foo(n: Int) = {
  val n = "hello"
  n * 3
}

Note: an existing question asks a similar but still conceptually very different question: Why does Scala support shadow variables? —that one asks about name shadowing in general, whereas I'm concerned with the fact that shadowing (unexpectedly) happens with parameters as well, where no obvious sub-scoping occurs—yes, there are the curly brackets, but one still (arguably) assumes the parameters are in the same scope.

EDIT: Haskell, the exemplar or FP languages, also allows this: foo x = let x = 4 in x is perfectly legal.

有时语言包含的功能不是因为它们被认为是好的和有用的,而是因为没有人考虑过。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM