简体   繁体   English

Scala isInstanceOf和type erasure

[英]Scala isInstanceOf and type erasure

I'm confused as how isInstanceOf works in Scala. 我很困惑isInstanceOf在Scala中是如何工作的。 If I do something like this: 如果我做这样的事情:

val x: Int = 5
x.isInstanceOf[Int]

Given that Scala does type erasure, shouldn't the JVM remove all type information during runtime? 鉴于Scala确实键入了擦除,JVM是否应该在运行时删除所有类型信息?

It's not all type information, just information about generic types . 它不是所有类型信息,只是关于泛型类型的信息。 Consider this: 考虑一下:

scala> val l = List("foo")
l: List[String] = List(foo)

scala> l.isInstanceOf[List[String]]
res0: Boolean = true

scala> l.isInstanceOf[List[Int]]
<console>:9: warning: fruitless type test: a value of type List[String] cannot also be a List[Int] (the underlying of List[Int]) (but still might match its erasure)
              l.isInstanceOf[List[Int]]
                            ^
res1: Boolean = true

They both return true , because the erased type is List . 它们都返回true ,因为擦除的类型是List

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

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