0

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.

4

2 回答 2

2

虽然在编译时编译器不知道K's 的类型,但在运行时你总是传入一个特定类型的对象。每个对象都知道它是什么类型。当您调用 时getClass,您正在调用对象的方法,因此您将返回其实际类型。

于 2014-07-22T06:55:58.650 回答
1

在运行时a(3)传递的值a3,现在如果编译器检查其值的类型,那么它当然会返回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
于 2014-07-22T06:38:19.797 回答