简体   繁体   English

路径依赖类型的方差技巧

[英]Variance trick with path-dependent types

Here's another one for implicits and path dependent types. 这是针对implicits和路径依赖类型的另一个。 I don't understand why I need to be so verbose here: (Note -- I found the answer, see below) 我不明白为什么我需要在这里如此冗长:(注意 - 我找到了答案,见下文)

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
}

first try: 第一次尝试:

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

second try: 第二次尝试:

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

third try: 第三次尝试:

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

the Scala 2.9 REPL helps us (thanks, whoever added this useful message!). Scala 2.9 REPL帮助我们(谢谢,无论谁添加了这个有用的消息!)。 Here for the test1 : 这里为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]
                       ^

Thus: changing trait C[ X ] to trait C[ -X ] makes test1 work as expected. 因此:将trait C[ X ]改为trait C[ -X ]使test1按预期工作。

Are you sure you want this.type ? 你确定要this.type Scala's "this type" is not the same as what is more commonly known as " MyType ". Scala的“这种类型”与通常所说的“ MyType ”不同。 See this discussion on this.type , as well as the discussion linked by the MyType question. 这个讨论this.type ,以及由MyType的问题联系在一起讨论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM