scala getClass and type erasure?

130 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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 call getClass, you are calling a method on the object, so you get back its actual type.

1
On

at run time a(3) the passed value to a is 3 and now if compiler checks its value's type then it ofcourse returns Integer

scala>   def a[K](key: K) = {
     |   println(key.getClass)
     |   }
a: [K](key: K)Unit

scala> a(3)
class java.lang.Integer

scala> a("34")
class java.lang.String

scala> a(34.34)
class java.lang.Double