Scala的isInstanceOf和类型擦除

3

我对Scala中的isInstanceOf如何工作感到困惑。如果我做了这样的事情:

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

鉴于Scala进行类型擦除,JVM在运行时是否应该删除所有类型信息?
1个回答

10

这并不是所有类型信息,只是关于通用类型的信息。考虑以下内容:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接