依赖类型不为构造函数工作? [英] Dependent types not working for constructors?

查看:105
本文介绍了依赖类型不为构造函数工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

依赖于路径的类型很有用:

Path-dependent types are useful:

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

为什么构造函数不起作用?

Why doesn't this work for constructors?

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

还是我只是做错了? p>

Or am I just doing it wrong?

推荐答案

这对我来说似乎是一个错误。 编辑:找到它,这是 SI-5712

This seems like a bug to me. Edit: found it, this is SI-5712.

2.9 SLS的§5.3节说:

Section §5.3 of the 2.9 SLS says:


(ps1)。 。 。 (psn)是类的主构造函数
的形式值参数子句。正式值参数的范围包括所有后续的
参数部分和模板t。

(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 .

有一个例外: / p>

There is an exception:


但是,正式的值参数
不能构成任何父类或$ b成员的类型的一部分$ b类模板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 .

但它说它不能是任何父类或成员类型的一部分,而不是以下参数部分中的任何,因此似乎不会禁止参数组之间的路径依赖类型。

But it says it cannot be part of the types of any of the parent classes or members, not of any of the following parameter sections, so it does not seems to forbid path-dependent types between argument groups.

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

You can go around this with a secondary constructor:

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

编辑:此辅助构造函数解决方法不是很好:暴露系统全局变得非常困难,因为只有主构造函数可以声明 val

Edit: this secondary constructor workaround is not very good: exposing system or global become very difficult because only the primary constructor can declare 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的建议好多了。

But this is getting awful. @senia's suggestion is much better.

这篇关于依赖类型不为构造函数工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆