I am a little puzzled by the getClass method when used in generic type case:
def a[K](key: K) = {
println(key.getClass)
}
Shouldn't this always been AnyRef or Any or something? Since type K info is not available in runtime?
but a(3)
will output Int
, and a("fdasf")
will output String.
Alright, this is a silly question, I get confused by the K and key's type information.
While at compile time the compiler doesn't know
K
's type, at runtime you are always passing in an object of a specific type. Every object knows what type it is. When you callgetClass
, you are calling a method on the object, so you get back its actual type.