Scala isInstanceOf 和类型擦除 [英] Scala isInstanceOf and type erasure
本文介绍了Scala isInstanceOf 和类型擦除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对 isInstanceOf
在 Scala 中的工作方式感到困惑.如果我这样做:
I'm confused as how isInstanceOf
works in Scala. If I do something like this:
val x: Int = 5
x.isInstanceOf[Int]
鉴于 Scala 会进行类型擦除,JVM 不应该在运行时删除所有类型信息吗?
Given that Scala does type erasure, shouldn't the JVM remove all type information during runtime?
推荐答案
这不是所有类型信息,只是关于泛型类型的信息.考虑一下:
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
它们都返回true
,因为擦除的类型是List
.
They both return true
, because the erased type is List
.
这篇关于Scala isInstanceOf 和类型擦除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文