为什么Scala方法isInstanceOf [T]不起作用

问题描述 投票:1回答:1

为什么isInstanceOf[T]方法无法按预期工作?

以下,我定义了一个hello类和伴随对象。在hello对象中,我在代码“ this.isInstanceOf[T]”的行中测试hel.typetest[Int],当类型trueT时,这是什么Int

    import scala.reflect.ClassTag

    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
scala api generics
1个回答
0
投票

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

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

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

[存在T时,也有针对ClassTag的模式匹配的特殊情况支持:

def typetest[T: ClassTag]: Unit = {
  Console.println(this match {
    case _: T => true
    case _ => false
  })
}
© www.soinside.com 2019 - 2024. All rights reserved.