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, don’t do this.
(My guess is that they are on a on a different scope level, e.g. class level and function level, and the compiler is using some kind of name mangling)
class MyTest[A](){
type MyType = A
def checkString[A](value:A, x:MyType):A = {
value match {
case x:String => println("Value is a String")
case _ => println("Value is not a String")
}
x match {
case x:String => println("x is a String")
case _ => println("x is not a String")
}
value
}
}
Example output from 2.8.0
scala> val test = new MyTest[Int]
test: MyTest[Int] = MyTest@308ff65f
scala> test.checkString("String",1)
Value is a String
x is not a String
res7: java.lang.String = String
scala> test.checkString(1,1)
Value is not a String
x is not a String
res8: Int = 1
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:
The principle is that a scope has control over its namespace. This has dangers, if you use it foolishly (e.g. I have used
Xandafor each of three different things, andAfor two–in fact, you could replace every identifier withXexcept for the one in theSomewhich 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.So be aware that you have the power to confuse yourself, and wisely choose to use that power non-confusingly.