Scala isInstanceOf和type erasure

时间:2014-07-23 00:46:51

标签: scala type-erasure

我很担心isInstanceOf在Scala中的运作方式。如果我做这样的事情:

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

鉴于Scala确实键入了擦除,JVM是否应该在运行时删除所有类型信息?

1 个答案:

答案 0 :(得分:9)

它不是所有类型信息,只是关于泛型类型的信息。考虑一下:

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

它们都返回true,因为已删除的类型为List