为什么 List[Int] 是 List[Boolean] 的实例? [英] Why is List[Int] an instance of List[Boolean]?

查看:53
本文介绍了为什么 List[Int] 是 List[Boolean] 的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 Scala REPL (Scala 2.9.1) 时,我看到了使用 isInstanceOf 方法的惊人结果:

As I played a bit with the Scala REPL (Scala 2.9.1) I saw a surprising result with the isInstanceOf method:

scala> val l = List[Int](1, 2, 3)
l: List[Int] = List(1, 2, 3)

scala> l.isInstanceOf[List[Int]]
warning: there were 1 unchecked warnings; re-run with -unchecked for details
res3: Boolean = true

scala> l.isInstanceOf[List[String]]
warning: there were 1 unchecked warnings; re-run with -unchecked for details
res4: Boolean = true

scala> l.isInstanceOf[List[Boolean]]
warning: there were 1 unchecked warnings; re-run with -unchecked for details
res5: Boolean = true

谁能解释一下最后两个结果?

Can anyone explain the last two results ?

推荐答案

re-running with -unchecked:

re-running with -unchecked:

scala> l.isInstanceOf[List[Int]]
<console>:9: warning: non variable type-argument Int in type List[Int] is 
unchecked since it is eliminated by erasure
              l.isInstanceOf[List[Int]]
                        ^

对象的具体类型在运行时是未知的.这是 JVM 提供的泛型机制的一般特性/限制.有关详细信息,请参阅键入擦除.

The specific type of the object is just not known at runtime. This is a general feature/limitation of the generics mechanism provided by the JVM. See Type erasure for more information.

这篇关于为什么 List[Int] 是 List[Boolean] 的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆