【问题标题】:Scala isInstanceOf and type erasureScala isInstanceOf 和类型擦除
【发布时间】:2014-07-23 00:46:50
【问题描述】:

我对 isInstanceOf 在 Scala 中的工作方式感到困惑。如果我这样做:

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

鉴于 Scala 确实进行了类型擦除,JVM 不应该在运行时删除所有类型信息吗?

【问题讨论】:

    标签: scala type-erasure


    【解决方案1】:

    这不是所有类型信息,只是关于泛型类型的信息。考虑一下:

    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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 2012-05-28
      • 1970-01-01
      • 2020-07-27
      • 2012-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多