【问题标题】:Variance trick with path-dependent types路径依赖类型的方差技巧
【发布时间】:2013-09-28 03:53:35
【问题描述】:

这是另一种用于隐式和路径相关类型的方法。我不明白为什么我需要在这里如此冗长:(注意——我找到了答案,见下文)

trait B
trait C[X]
trait A { def call[B1 <: B](implicit b: B1): C[B1] }
trait D extends B {
  def set(c: C[this.type]): Unit
}

第一次尝试:

def test1(a: A)(implicit d: D: Unit =
  d.set(a.call) // found C[D] -- required C[d.type]

第二次尝试:

def test2(a: A)(implicit d: D): Unit =
  d.set(a.call[d.type]) // could not find implicit value for parameter b: d.type

第三次尝试:

def test3(a: A)(implicit d: D): Unit =
  d.set(a.call[d.type](d))  // works. why so much clutter!?

【问题讨论】:

    标签: scala implicit variance path-dependent-type


    【解决方案1】:

    Scala 2.9 REPL 帮助了我们(感谢添加此有用信息的人!)。这里为test1

     found   : C[D]
     required: C[d.type]
    Note: D >: d.type, but trait C is invariant in type X.
    You may wish to define X as -X instead. (SLS 4.5)
                  d.set( a.call ) // found C[D] -- required C[d.type]
                           ^
    

    因此:将trait C[ X ] 更改为trait C[ -X ] 使test1 按预期工作。

    【讨论】:

    • 这并不意味着您想要 C 是反变体。 d.type 是比 D 更具体的类型——它是每个实例的单例类型。
    • 事实上,没过多久,我就碰到了下一堵墙,X 必须用在一个不变的位置上。这种类型约束的东西怎么会是这样的 PITA
    【解决方案2】:

    你确定要this.type吗? Scala 的“这种类型”与通常所说的“MyType”不同。请参阅 this.type 上的 this discussion,以及 MyType 问题链接的讨论。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-17
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    相关资源
    最近更新 更多