简体   繁体   English

Scala的getClass和类型擦除?

[英]scala getClass and type erasure?

I am a little puzzled by the getClass method when used in generic type case: 在泛型类型的情况下使用时,我对getClass方法感到有些困惑:

def a[K](key: K) = {
  println(key.getClass)
}

Shouldn't this always been AnyRef or Any or something? 这不应该一直是AnyRef或Any或其他东西吗? Since type K info is not available in runtime? 由于类型K信息在运行时不可用?

but a(3) will output Int , and a("fdasf") will output String. 但是a(3)将输出Int ,而a("fdasf")将输出String.


Alright, this is a silly question, I get confused by the K and key's type information. 好吧,这是一个愚蠢的问题,我对K和key的类型信息感到困惑。

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. 在编译时,编译器不知道K的类型,而在运行时,您总是传递特定类型的对象。 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. 调用getClass ,您正在对对象调用方法,因此可以获取其实际类型。

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 在运行时a(3)传递给a值是3 ,现在,如果编译器检查其值的类型,则它当然会返回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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM