0

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

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!?
4

2 回答 2

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工作。

于 2011-04-05T02:26:13.760 回答
1

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

于 2011-04-05T14:17:42.233 回答