参数类型不是反变体吗?
我理解术语协方差和反方差。但有一件小事我无法理解。在课程中的Scala中的函数式编程课程中,Martin Ordersky提到:
I understand the terms co-variance and contra-variance. But there is one small thing I am unable to understand. In the course "Functional Programming in Scala" on coursera, Martin Ordersky mentions that:
函数在其参数类型和共变量中是逆变的在
中他们的返回类型
Functions are contravariant in their argument types and co-variant in their return types
所以例如在Java中,让 Dog
extends Animal
。让函数成为:
So for example in Java, let Dog
extends Animal
. And let a function be :
void getSomething(Animal a){
我有函数调用
Dog d = new Dog();
getSomething(d)
所以基本上发生的事情是动物a = d
。根据 wiki ,协方差是将范围扩大到更窄。而且我们正在从狗转变为动物。 SO不是参数类型协变而不是逆变?
So basically what is happeneing is that Animal a = d
. And according to wiki covariance is "Converting wider to narrow". And above we are converting from dog to Animal. SO isnt the argument type covariant rather than contravariant?
trait Function1 [-T1, +R] extends AnyRef
英文,参数 T1
是逆变的,结果类型 R
是协变的。这是什么意思?
In English, parameter T1
is contravariant and result type R
is covariant. What does it mean?
当某段代码需要 Dog =>的函数时动物
类型,你可以提供 Animal =>的函数。动物
类型,这要归功于参数的逆转(你可以使用更广泛的类型)。
When some piece of code requires a function of Dog => Animal
type, you can supply a function of Animal => Animal
type, thanks to contravariance of parameter (you can use broader type).
你还可以提供的功能狗=>狗
类型,感谢结果类型的协方差(你可以使用更窄的类型)。
Also you can supply function of Dog => Dog
type, thanks to covariance of result type (you can use narrower type).
这实际上是有道理的:有人想要一个函数来转换狗对任何动物。您可以提供转换任何动物(包括狗)的功能。此外,您的功能只能返回狗,但狗仍然是动物。
This actually makes sense: someone wants a function to transform dog to any animal. You can supply a function that transforms any animal (including dogs). Also your function can return only dogs, but dogs are still animals.