路径相关类型的方差技巧

这是针对implicits和路径依赖类型的另一个。我不明白为什么我需要在这里如此冗长:(注意 - 我找到了答案,见下文)
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 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
按预期工作。     
你确定要
this.type
吗? Scala的“这种类型”与通常所说的“MyType”不同。请参阅
this.type
上的此讨论,以及MyType问题链接的讨论。     

要回复问题请先登录注册