为什么Scala方法isInstanceOf [T]无法正常工作

为什么isInstanceOf[T]方法不能按预期运行?

在下面,我定义了一个hello类和伴随对象。在hello对象中,我在代码“ this.isInstanceOf[T]”行中测试了hel.typetest[Int],当类型trueT时,Int为何呢? / p>

object hello {
  def main(args: Array[String]): Unit = {
    Console.println("main")
    val hel = new hello
    hel.typetest[Int]
  }
}

class hello {
  def typetest[T: ClassTag]: Unit = {
    Console.println(this.isInstanceOf[T])
    Console.println(this.getclass)
  }
}

输出:

main
true
class hello
eiance 回答:为什么Scala方法isInstanceOf [T]无法正常工作

由于type erasure(以及拳击)。 T会擦除为Object,因此this.isInstanceOf[T]在字节码中变为this.isInstanceOf[Object],始终为真。

碰巧,ClassTag旨在避免这种情况,但是您实际上需要使用它而不是调用isInstanceOf

def typetest[T](implicit tag: ClassTag[T]): Unit = {
  Console.println(tag.runtimeClass.isInstance(this))
}

在存在T的情况下,还有一种特殊情况的support用于与ClassTag进行模式匹配:

def typetest[T: ClassTag]: Unit = {
  Console.println(this match {
    case _: T => true
    case _ => false
  })
}

有人建议在存在is的情况下使asInstanceOf[T] / ClassTag正常工作,但是编译器中内置了一些假设,可以防止这种情况,并且很难更改(如果我没记错的话)。

本文链接:https://www.f2er.com/2845507.html

大家都在问