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

scala – 依赖类型不适用于构造函数?

发布时间:2020-12-16 09:11:51 所属栏目:安全 来源:网络整理
导读:路径相关类型很有用: trait Sys { type Global}def foo[S : Sys](system: S)(global: system.Global) = () 为什么这不适用于构造函数? class Foo[S : Sys](val system: S)(val global: system.Global) 还是我只是做错了? 解决方法 这似乎是我的错误.编辑
路径相关类型很有用:

trait Sys {
  type Global
}
def foo[S <: Sys](system: S)(global: system.Global) = ()

为什么这不适用于构造函数?

class Foo[S <: Sys](val system: S)(val global: system.Global)

还是我只是做错了?

解决方法

这似乎是我的错误.编辑:发现它,这是 SI-5712.

2.9 SLS的§5.3节说:

(ps1 ) . . . (psn ) are formal value parameter clauses for the primary constructor
of the class. The scope of a formal value parameter includes all subsequent
parameter sections and the template t .

有一个例外:

However,a formal value parameter
may not form part of the types of any of the parent classes or members of the
class template t .

但是它表示它不能是任何父类或成员的类型的一部分,而不是以下任何参数部分,因此它似乎不禁止参数组之间的路径相关类型.

你可以用二次构造函数来解决这个问题:

class Foo[S <: Sys] private[this] () {
  def this(system: S)(global: system.Global) = this
}

编辑:这个辅助构造函数解决方法不是很好:暴露系统或全局变得非常困难,因为只有主构造函数才能声明vals.

一个演员的例子:

class Foo[S <: Sys] private[this] () {
  private[this] var _system: S = _
  private[this] var _global: system.Global = _

  def this(system0: S)(global0: system0.Global) = {
    this
    _system = system0
    _global = global0.asInstanceOf[system.Global]
  }

  lazy val global: system.Global = _global
  lazy val system: S = _system
}

但是这变得非常糟糕. @ senia的建议好多了

(编辑:李大同)

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

    推荐文章
      热点阅读