+ - 签署Scala中的通用声明 [英] +- Signs in Generic Declaration in Scala
问题描述
trait PartialFunction [-A,+ B]扩展(A)⇒B
也许有人可以帮助澄清泛型声明中加号和减号的意义吗?
+和 - 的意思是协变和逆变类型。总之,这意味着:
$ b preartialFunction [-A1,+ B1] <: PartialFunction [-A2,+ B2]
仅当 A1:> A2
和 B1 <:B2
,其中<:
是子类型关系。
- 通常用于输入参数,+用于输出 - 在C#中,它们甚至在 >和 out
。在存在类型上构建的还有一些更原始的 Java中的通用差异支持 - 实际上你可以用 _< ;: SomeType
(协方差)或抽象类型成员类型T< ;: SomeType
在Scala中。
没有修饰符 PartialFunction [A1,B1]
与 PartialFunction [A2,B2]
(换句话说,它将是不变的)。
这种类型也有一些限制,例如协变(+)类型不能处于逆向位置(只能从方法返回),反之亦然。这是为了支持 Liskov替代原则,可以通过in/out自然理解,解释。
另外,值得注意的是 A => B
(语法糖用于 Function1
)本身使用了co- / contra-variance:
trait Function1 [-T1,+ R]扩展AnyRef
I was looking at the documentation for PartialFunction in this link:
trait PartialFunction[-A, +B] extends (A) ⇒ B
Maybe someone can help clarify the significance of the plus and minus signs in the generic declaration?
"+" and "-" mean covariant and contravariant types respectively. In short, it means that:
PartialFunction[-A1, +B1]
<: PartialFunction[-A2, +B2]
only if A1 :> A2
and B1 <: B2
, where <:
is subtyping relationship.
"-" usually applied for input parameters, "+" for output - in C# they even use respective keywords in
and out
. There is also some more primitive generic variance support in Java built up on existential types - actually you can do it using _ <: SomeType
(covariance) or abstract type members type T <: SomeType
in Scala as well.
Without modifiers PartialFunction[A1, B1]
would have no direct relationship to a PartialFunction[A2, B2]
(in other words, it would be invariant).
P.S. There are also some restrictions applied to such types, like covariant("+") type can't be in contravariant position (you can only return it from a method) and vice-versa. This is done in order to support Liskov Substitution Principle and naturally understandable by "in"/"out" interpretation.
Also, it worth noticing that A => B
(syntax sugar for Function1
) itself is using co-/contra-variance:
trait Function1 [-T1, +R] extends AnyRef
这篇关于+ - 签署Scala中的通用声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!