且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

有关Scala中协方差的一些问题

更新时间:2023-09-29 22:07:04

您不能编写 def append(x:Sequence [A]):Sequence [A ]} ,因为A在 append 变量中处于协变位置,同时是协变的。

You can't write def append(x: Sequence[A]): Sequence[A]}, as A is in contravariant position in the append argument, while being covariant.

您应该这样写:

abstract class Sequence[+A] {
   def append[B >: A](x: Sequence[B]): Sequence[B]
}

您在示例为何不进行编译,又(共,对和和-内)方差如何工作?

简而言之:

+ A表示将A转换为A的超类型是安全的上下文(狗可能会转换为动物)。如果您编写 append [A](x:Sequence [A]),则表示x只能是A或A的子类型(狗,yorsay等),但决不能一个超类型(例如Animal),因此这与+ A注释矛盾,并且在编译时失败。使用签名 append [B&gt ;: A](x:Sequence [B]),可以通过避免在函数参数中命名A来解决此问题。

+A states that it is safe to convert this A to a supertype of A in all context ( A Dog maybe converted to an Animal). If you write append[A](x: Sequence[A]) you are stating that x can only be A or subtypes of A (Dog, yorsay etc), but never a supertype (like Animal), so this contradicts the +A annotation and fails at compilation time. With the signature append[B >: A](x: Sequence[B]) you fix it by avoiding naming A in the function arguments.

因此, [B&gt ;: A] 定义了B的下限,指出B必须是A的超类型,或者A,但从不在层次结构中低于A的任何类中,因此符合+ A签名。

So, [B >: A] is defining a lower bound for B, stating that B must be a supertype of A, or A, but never any class below A in the hierarchy, and hence complying with +A signature.

我知道协方差和协变是复杂的概念,很难理解,我也会不时感到困惑。

I know covariance and contravariance are complex concepts and hard to understand, I also get confused from time to time.