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

scala – 关于this.type的令人惊讶的等价和非等价

发布时间:2020-12-16 18:49:06 所属栏目:安全 来源:网络整理
导读:无论是从Trait内部还是从创建对象的范围引用this.type,都会产生不同的结果. import scala.reflect.runtime.universe._trait Trait { val ttag = typeOf[this.type] println(s"Trait constructor: $this")}object Instance1 extends Traitobject Instance2 ex
无论是从Trait内部还是从创建对象的范围引用this.type,都会产生不同的结果.

import scala.reflect.runtime.universe._

trait Trait {
  val ttag = typeOf[this.type]
  println(s"Trait constructor: $this")
}

object Instance1 extends Trait

object Instance2 extends Trait

println(typeOf[Instance1.type] =:= typeOf[Instance2.type])  // Should be false
println(Instance1.ttag =:= Instance2.ttag)                  // Should be false
println(Instance1.ttag =:= typeOf[Instance1.type])          // Should be true

这是输出:

false    // As expected: the singleton types of two objects are different.
Trait constructor: $line9.$read$$iw$$iw$$iw$$iw$Instance1$@58c46295
Trait constructor: $line10.$read$$iw$$iw$$iw$$iw$Instance2$@452451ba
true     // But the this.type tags are equivalent
false    // and the this.type tag is not equivalent to the singleton type.

因此,有两个不同的对象,但显然每个对象都为其this.type获取一个等效的类型标记,它不等同于从封闭范围看到的对象的.type.

这是一个编译器错误,或者,如果没有,你能解释为什么这种行为有意义吗?

(我正在运行Scala 2.11.2.我已尝试使用自己的别名,结果相同.)

解决方法

以下程序打印false然后为true.在我看来,这两种情况之间应该没有实质性区别(虽然这更像是一种意见;我不能说真的是否有原因):

import scala.reflect.runtime.universe._

object Test2 extends App {
  def foo(): Type = {
    object a
    typeOf[a.type]
  }

  println(foo() =:= foo()) // false

  trait Trait {
    val ttag = typeOf[this.type]
  }

  object Instance1 extends Trait

  object Instance2 extends Trait

  println(Instance1.ttag =:= Instance2.ttag) // true
}

(编辑:李大同)

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

    推荐文章
      热点阅读