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

编程入门 行业动态 更新时间:2024-10-24 14:21:56
本文介绍了有关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中协方差的一些问题

本文发布于:2023-10-28 18:00:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1537369.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:协方差   Scala

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!