Erik Kaplun
Erik Kaplun

Reputation: 38227

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.

P.S. 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.

Upvotes: 3

Views: 231

Answers (1)

TwoThe
TwoThe

Reputation: 14289

Sometimes languages contain features not because they are considered to be good and useful, but because no one considered at all.

Upvotes: 1

Related Questions