pla*_*pus 8 compiler-construction type-systems scala variance
在Scala编程第436页中,作者给出了编译器检查每个类型参数仅用于适当分类的位置的示例.
abstract class Cat[-T, +U] {
def meow[W^-](volume: T^-, listener: Cat[U^+, T^-]^-) : Cat[Cat[U^+, T^-]^-, U^+]^+
}
Run Code Online (Sandbox Code Playgroud)
该示例如何运作?为什么W和第一个T得到负号?算法如何实际工作?
http://www.artima.com/pins1ed/type-parameterization.html
第一版中的 19.4。
“方法值参数位置被分类为相对于方法外部位置的翻转分类。”
“除了方法值参数位置之外,当前的分类还针对方法的类型参数进行了翻转。”
在这种情况下翻转意味着“从正翻转”,因此是负的。
为了获得奖励积分,请生成一个 LOLcats 来说明该模型的物理解释。
附加问答:
Okay let's look at the 3rd value parameter "listener".
It has a annotation of: Cat[U^+, T^-]^-.
Why does U have +? Why does T have -? Why does the whole thing have a -?
Run Code Online (Sandbox Code Playgroud)
方法参数是逆变位置,因此是最外面(最右边)的减号。
Cat 的类型参数是 [-T, +U],因此在这个翻转位置中,是 [+, -]。(所应用的实际参数 [U, T] 不相关。)它进行检查,因为实际参数分别是协变和逆变的。
更多问题:
Could you kindly describe on SO why the return value type has the following annotation
for the sake of completeness...
Also could you be so kind as to give an example of the following rule?
A classification is sometimes flipped at the type argument position of a type...
Run Code Online (Sandbox Code Playgroud)
第二个附加问题与您之前的第一个附加问题相同。两个Cat[+,-]表示翻转,结果类型Cat[-,+]表示不翻转。
该线程为参数(传入的内容)和结果(输出的内容)的变化提供了进一步的动机:
https://groups.google.com/forum/#!topic/scala-user/ViwLKfvo3ec
我发现 Java 讨论和示例(PECS 或 Naftalin 和 Wadler)对 Scala 提供的内容很有帮助。