【问题标题】:Scala: How is instance of Any also instance of Subtypes, Int, Boolean etcScala:Any的实例也是子类型,Int,Boolean等的实例
【发布时间】: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 而不是 typeisInstsnceOfruntime 检查,而不是 compile-time 检查。在 JVM 运行时中没有types 只有classes。 - this 博客文章比迄今为止提供的任何答案都更清楚地回答了这个问题。

标签: scala scala-collections


【解决方案1】:

当你写作时,

val s: String = "a sample string"

你有 3 个非常独立的东西,

  1. immutable variable 类型为 String
  2. 一个identifier s 标识上述variable
  3. String 类型的instance,上面的variable 将此instance 称为value

现在,A 类型的 variable 可以引用 B 类型的任何实例,只要 BA 的子类型。

所以,如果你写,

val a: Any = "another sample string"

您会得到一个identifier a 标识一个immutable variable 类型的Any 引用一个String 类型的实例。

因此,如果您检查a.isInstanceOf[String],您将得到true,因为a 引用的实例是String 类型。

【讨论】:

    猜你喜欢
    • 2014-11-29
    • 2023-03-19
    • 2013-06-10
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    • 1970-01-01
    相关资源
    最近更新 更多