加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 类的实例与其伴随对象之间的关系

发布时间:2020-12-16 10:00:56 所属栏目:安全 来源:网络整理
导读:我有以下类和伴侣对象: class TestMatch(val i: Int)object TestMatch{ def apply(i: Int) = new TestMatch(i) def unapply(tm : TestMatch): Option[Int] = Some(tm.i)} 现在考虑以下简单程序: println("isAssignableFrom: " + classOf[TestMatch].isAssi
我有以下类和伴侣对象:

class TestMatch(val i: Int)

object TestMatch{
  def apply(i: Int) = new TestMatch(i)
  def unapply(tm : TestMatch): Option[Int] = Some(tm.i)
}

现在考虑以下简单程序:

println("isAssignableFrom: " + classOf[TestMatch].isAssignableFrom((tm.getClass)))
println("equality: " + classOf[TestMatch].equals((tm.getClass)))
println("instanceOf:" + TestMatch.isInstanceOf[TestMatch])

它打印:

isAssignableFrom: true
equality: true
instanceOf:false

这怎么可能?还没有在Java中遇到这个问题.

解决方法

在每个示例中,您没有提到相同的TestMatch概念.

> classOf [TestMatch]和instanceOf [TestMatch]将TestMatch称为类型.单身人士没有定义类型.
> TestMatch.something()是对单例对象TestMatch的方法的调用

现在可能有点令人困惑的是:

object Singleton
println(Singleton.isInstanceOf[Singleton]) // prints true

我猜测当单例是伴随对象时,Scala会优先考虑类.

编辑:

正如Alexey Romanov所指出的那样,scala.Singleton实际上是在Scala SDK中定义的,每个单例对象都会扩展…让我们再来一个不同的名字:

object MySingleton
println(MySingleton.isInstanceOf[MySingleton])

这不会编译,因为单例不定义类型.有一种方法可以编译.

println(MySingleton.isInstanceOf[MySingleton.type]) // true

这就是你如何证明你不是指同一件事.最后的例子,我们试试吧

class MyClassWithCompanion
object MyClassWithCompanion

val x = new MyClassWithCompanion

println(MyClassWithCompanion.isInstanceOf[MyClassWithCompanion])      // false
println(MyClassWithCompanion.isInstanceOf[MyClassWithCompanion.type]) // true
println(MyClassWithCompanion.isInstanceOf[x.type]                     // false

这很微妙,但这意味着什么:

> .type是应用于实例并返回其类型的运算符> x.type只能在x是某个实例的情况下定义,因此除非此类具有伴随对象,否则MyClass.type将无法编译.因此,MyClassWithCompanion.type必然引用伴随对象(它是一个实例)而不是类本身>伴侣的类型和类本身的类型是不同的.你无法用单例X替换X的实例,这是有道理的,因为它们具有不同的性质.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读