【发布时间】:2020-02-13 22:45:22
【问题描述】:
class Parent
class Child extends Parent
val p = new Parent
val c = new Child
p.isInstanceOf[Parent] // Return true
p.isInstanceOf[Child] // false,
c.isInstanceOf[Child] // Return true
c.isInstanceOf[Parent] // true as Child is a subtype of Parent
所以我们有上述行为。现在,根据我在 Scala 初学者时代所读过的有关 Scala 的内容,Any 是所有类的超类型。所有值类型,Int、Boolean、Double 等都是 Any 的子类型。
因此,Int、Boolean 等子类型的任何值也将是 Any 类型。但反之亦然。
val i: Int = 10
i.isInstanceOf[Int] // true
i.isInstanceOf[Any] // true
val a: Any = 5
a.isInstanceOf[Any] // true. Everything until now, inline with the Parent, Child example above
a.isInstanceOf[Int] // Returns true as well. How? a is of Any type and Int is a Subtype of Any, then how is a value of Any type, also of type Int.
【问题讨论】:
-
简而言之,isInstanceOf 不检查声明类型。它检查底层对象类型。
-
@texabruce 实际上它检查的是底层对象 class 而不是 type。
isInstsnceOf是 runtime 检查,而不是 compile-time 检查。在 JVM 运行时中没有types 只有classes。 - this 博客文章比迄今为止提供的任何答案都更清楚地回答了这个问题。