【发布时间】:2020-04-18 11:12:30
【问题描述】:
为什么isInstanceOf[T] 方法没有按预期工作?
在下文中,我定义了一个hello 类和伴随对象。在 hello 对象中,我在代码行“hel.typetest[Int]”中测试了this.isInstanceOf[T],当T 类型为Int 时,为什么这是true?
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
【问题讨论】:
-
通常使用
isInstanceOf是不好的风格。它无法检查泛型类型(然后是大多数集合)。文档:scala-lang.org/api/2.12.1/scala/…
标签: scala generics reflection instanceof type-erasure