为什么方法的类型位置被标记为负数? [英] Why the type position of a method is marked as negative?
问题描述
对不起,我问了一些这样的问题,但我仍然没有得到明确的答案,也许我的英语不好,表达不清,让善良的人感到困惑.
Sorry I have asked some questions like this one, but I still can't get a clear answer, maybe my bad English and unclear expression puzzled the kind people.
当我阅读本文中的类型参数化"时:http://www.artima.com/pins1ed/type-parameterization.html,我看到有一些关于类型位置的解释:
When I read the "Type Parameterization" in this article: http://www.artima.com/pins1ed/type-parameterization.html, I see there are some explanation about the type positions:
作为一个有点人为的例子,考虑下面的类定义,其中几个位置的方差用 ^+(正)或 ^-(负)注释:
As a somewhat contrived example, consider the following class definition, where the variance of several positions is annotated with ^+ (for positive) or ^- (for negative):
abstract class Cat[-T, +U] {
def meow[W^-](volume: T^-, listener: Cat[U^+, T^-]^-)
: Cat[Cat[U^+, T^-]^-, U^+]^+
}
除了W
位置,我能理解这个类的大部分内容.我不明白为什么它标记为否定,并且整个文档中没有解释.
I can understand most of this class, except the W
position. I don't understand why it marked as negative, and there is no explanation in the whole document.
它还说:
带+注释的类型参数只能用在正数位置,带-注释的类型参数只能用在负数位置.
Type parameters annotated with + may only be used in positive positions, while type parameters annotated with - may only be used in negative positions.
如何在位置 W
中找到带有 -
注释的类型以适合此负位置?
How can I find a type with -
annotation in position W
to fit this negative position?
推荐答案
语言参考说:
- 方法参数的方差位置与封闭参数子句的方差位置相反.
- 类型参数的方差位置与封闭类型参数子句的方差位置相反.
- 类型声明或类型参数下界的方差位置与类型声明或参数的方差位置相反.
好的,类型参数具有方差位置意味着什么?
OK what does it mean for a type parameter to have a variance position?
class Moo[+A, -B] {
def foo[X] (bar : Y) ...
所以 Y 处于逆变位置,这很明显.我们可以把 B 放在它的位置,但不能把 A.
So Y is in a contravariant position, this is clear. We can put B in its position, but not A.
但是 X 处于逆变位置意味着什么?我们不能替换 A 或 B 或那里的任何东西,它只是一个形式参数!
But what does it mean for X to be in a contravariant position? We cannot substitute A or B or anything there, it's just a formal parameter!
这是真的,但是这个东西可以有从属位置,它们是类型,并且有变化.所以在跟踪我们翻转方差的次数时,我们需要计算 X 的位置.这里没有 X 的从句,但考虑一下:
That's true, but this thing can have subordinate positions which are types, and have variance. So we need to count the position of X when tracking how many times we flip variance. There's no subordinate clauses of X here, but consider this:
class Moo[+A, -B] {
def foo[X >: Z] (bar : B) ...
我们可能可以用 A 或 B 替换 Z,但哪个是正确的?那么,Z的位置和X的位置相反,X的位置和顶层的位置相反,是协变的,所以Z也一定是协变的.让我们检查一下:
We probably can replace Z with either A or B, but which is correct? Well, the position of Z is the opposite of that of X, and the position of X is the opposite of that of the top-level, which is covariant, so Z must be covariant too. Let's check:
abstract class Moo[+A, -B] {
def foo[X >: A] (bar : B)
}
defined class Moo
看起来我们是对的!
这篇关于为什么方法的类型位置被标记为负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!