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

scala – 通过类型成员而不是类型参数进行F限制量化?

发布时间:2020-12-16 09:03:20 所属栏目:安全 来源:网络整理
导读:我想将类型参数移动到类型成员. 这是起点: trait Sys[S : Sys[S]] { type Tx type Id : Identifier[S#Tx]}trait Identifier[Tx] { def dispose()(implicit tx: Tx): Unit}trait Test[S : Sys[S]] { def id: S#Id def dispose()(implicit tx: S#Tx) { id.dis
我想将类型参数移动到类型成员.

这是起点:

trait Sys[S <: Sys[S]] {
  type Tx
  type Id <: Identifier[S#Tx]
}

trait Identifier[Tx] {
  def dispose()(implicit tx: Tx): Unit
}

trait Test[S <: Sys[S]] {
  def id: S#Id
  def dispose()(implicit tx: S#Tx) {
    id.dispose()
  }
}

让我烦恼的是,我在整个图书馆里都带着一个类型参数[S<:Sys [S]].所以我在想的是:

trait Sys {
  type S = this.type  // ?
  type Tx
  type Id <: Identifier[S#Tx]
}

trait Identifier[Tx] {
  def dispose()(implicit tx: Tx): Unit
}

trait Test[S <: Sys] {
  def id: S#Id
  def dispose()(implicit tx: S#Tx) {
    id.dispose()
  }
}

哪个失败了…… S#Tx和S#Id在某种程度上分离了:

error: could not find implicit value for parameter tx: _9.Tx
               id.dispose()
                         ^

任何使其有效的技巧或变化?

编辑:为了澄清,我主要希望修复Sys中的类型S以使其工作.在我的案例中使用路径依赖类型存在许多问题.举一个例子来反映pedrofuria和Owen的答案:

trait Foo[S <: Sys] {
  val s: S
  def id: s.Id
  def dispose()(implicit tx: s.Tx) {
    id.dispose()
  }
}

trait Bar[S <: Sys] {
  val s: S
  def id: s.Id
  def foo: Foo[S]
  def dispose()(implicit tx: s.Tx) {
    foo.dispose()
    id.dispose()
  }
}

<console>:27: error: could not find implicit value for parameter tx: _106.s.Tx
               foo.dispose()
                          ^

尝试制作那个def foo:Foo [s.type]让你知道这无处可去.

解决方法

这是一个编译的Test版本:

trait Test[S <: Sys] {
  val s : S
  def id: s.Id
  def dispose()(implicit tx: s.Tx) {
    id.dispose()
  }
}

你绝对正确地说“S#Tx和S#Id在某种程度上脱离了”.根据我的理解,你无法保证在两个S中它们实际上是同一类型.

(编辑:李大同)

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

    推荐文章
      热点阅读