【问题标题】:Why does Scala compiler say that contravariant type A occurs in covariant position in type >: A <: Any of type B?为什么Scala编译器说逆变类型A出现在类型>的协变位置:A <:任何类型B?
【发布时间】:2013-02-03 23:19:14
【问题描述】:

编译器告诉我这不能是警告:“逆变类型 A 出现在类型 > 的协变位置:A

trait Foo[-A]{
  def compose[B >: A](t: Foo[B]): Foo[A] = t andThen this
  def andThen[B <: A](t: Foo[B]): Foo[B]
}

我需要的只是一个可以分解的例子。那我就开心了。

【问题讨论】:

    标签: scala covariance contravariance


    【解决方案1】:

    正如错误所说,A 的方差注释是错误的。您不能在作为协变位置的返回类型中使用 A。想象一下,您在 Foo 中有另一种方法,它在适当的逆变位置(作为参数)使用 A

    trait Foo[-A] {
      ...
      def foo(a: A): Unit
    }
    

    现在您可以看到这是如何崩溃的:

    • Foo[-A] 意味着 Foo[X] &lt;: Foo[Y] 如果 X &gt;: Y
    • 返回值可能是声明的返回类型的子类型
    • 因此,如果-A 在这里是合法的,compose 可能会为某些A1 &gt;: A 返回一个Foo[A1]
    • trait Xtrait Y extends X { def bar() }
    • 想象一个Foo[Y],其中foo调用a.bar()
    • 因此,如果允许compose 返回Foo[X],它将中断

    因此,对于要编译的示例,A 必须是不变的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-29
      • 2018-01-16
      • 2017-12-28
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 2021-08-25
      相关资源
      最近更新 更多