有关Scala中协方差的一些问题 [英] Some questions about covariance in Scala

查看:75
本文介绍了有关Scala中协方差的一些问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解Scala中的协方差,但是找不到任何可以帮助解决此问题的示例。
我有以下代码:

I'm trying to understand covariance in Scala, but I cant find any examples that help me with this problem. I' ve got this code:

    class GenericCellImm[+T] (val x: T) {}

它可以很好地编译,但是当我使用它时

and it compile well, but when I use it

    class GenericCellMut[+T] (var x: T) { }

它不会编译。为什么在编写此代码时不能使用var(但可以使用val)?我该如何解决?
这也是类似的情况

it doesn't compile. Why I can't use var (but I can use val) when I'm writing this code? How can I fix it? Also here is similar situation

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

出了什么问题?

推荐答案

您不能编写 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> ;: 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> ;: 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.

这篇关于有关Scala中协方差的一些问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆