为什么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
是不好的编程风格。它无法检查泛型类型(以及大多数集合)。文档:https://www.scala-lang.org/api/2.12.1/scala/Any.html#isInstanceOf[T0]:Boolean - Mikhail Ionkin