我对 isInstanceOf
在 Scala 中的工作方式感到困惑。如果我这样做:
val x: Int = 5
x.isInstanceOf[Int]
鉴于 Scala 确实进行类型删除,JVM 不应该在运行时删除所有类型信息吗?
最佳答案
这不是所有类型信息,只是关于泛型类型的信息。考虑一下:
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
。
关于Scala isInstanceOf 和类型删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24900143/