I am wondering why the two type parameters (named \"A\") with the same name (\"A\") is allowed as per the example below. I know this is a POOR naming of type parameters, do
Nested scopes in Scala are free to shadow each others' symbol tables. Types are not the only things you can do this with. For example:
class X[A](a: A) {
def X[A](a: A) {
if (a==this.a) {
val X = Some(this.a)
X match {
case Some(a) => "Confused much yet?"
case _ => "Just because you can do this doesn't mean you should."
}
}
}
}
The principle is that a scope has control over its namespace. This has dangers, if you use it foolishly (e.g. I have used X
and a
for each of three different things, and A
for two--in fact, you could replace every identifier with X
except for the one in the Some
which has to be lower case). But it also has benefits when writing functional code--you don't have to worry about having to rename some iterating variable or type or whatever just because you happen to place it in a different context.
def example = {
val a = Array(1,2,3,4,5)
val sumsq = a.map(i => i*i).sum
a.map(i => {
val a = Array.range(1,i)
val sumsq = a.map(i => i*i).sum // Cut and paste from above, and works!
sumsq + i
}).sum
}
So be aware that you have the power to confuse yourself, and wisely choose to use that power non-confusingly.