为什么列表[INT]列表[布尔]的实例?(Why is List[Int] an instance

2019-09-18 03:32发布

正如我打了一下与斯卡拉REPL(斯卡拉2.9.1)我看到的方法isInstanceOf一个令人惊讶的结果:

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

谁能解释的最后两个结果?

Answer 1:

重新运行与-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提供的泛型机构的一般特征/限制。 见类型擦除以获取更多信息。



Answer 2:

这是由于类型擦除与约束它所能找到的最普通类型替换int类型参数列表。 在这种情况下,我相信这是scala.Any。

注意,这些也将产生真正的:

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

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

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

使用javap的拆解这个简单的类,我们可以看到,其实是在列表中没有泛型类型[INT]:

class Bar{
  val list = List[Int](1,2,3)
}

在拆卸Scala代码:

public class Bar extends java.lang.Object implements scala.ScalaObject{
  public scala.collection.immutable.List list();
  public Bar();
}


文章来源: Why is List[Int] an instance of List[Boolean]?
标签: scala