Scala:参数互变量和返回类型为何协变量? [英] Scala: arguments contravariant and return types are covariant why?
问题描述
Martin提到在Scala FP课程中,参数是相反的,而返回类型是协变的。我不认为我完全理解-有人可以帮忙吗?
In the FP in Scala course, Martin mentions, the arguments are "contravariant" while the return types are "covariant". I don't think I understood that completely - can someone help with this one?
推荐答案
假设 Bo黑猩猩
扩展了 Animal
,您有一个 Animal类型的函数
。在其他地方,您具有类型 foo
=> no黑猩猩 Bonobo =>的变量
。是否应该允许您将 bar
。动物 foo
分配给 bar
?当然:
Assume Bonobo
extends Animal
and you have a function foo
of type Animal => Bonobo
. In some other place you have a variable bar
of type Bonobo => Animal
. Should you be allowed to assign foo
to bar
? Sure:
-
foo
期望仅动物作为参数(太宽或过于笼统,与bar
的预期参数类型Bonobo
相比,因此是相反的),但没有处理li黑猩猩时出现问题。 - 您会从
foo
(比起太窄或太特殊bar
的预期返回类型Animal
,因此是协变的),但这很好,因为bar
希望能够处理各种动物
foo
expects just an animal as argument (which is "too wide" or "too general" compared to the expected argument typeBonobo
ofbar
, hence contravariant), but it has no problem processing a bonobo.- you get a bonobo back from
foo
(which is "too narrow" or "too special" compared to the expected return typeAnimal
ofbar
, hence covariant), but this is fine, as the caller ofbar
expects to deal with all kinds of animals
但是您不能打开这个例子周围,您不能分配 Bonobo => Animal
函数,其中 Animal => no黑猩猩
函数是预期的,因为该参数不合适(它可能得到的动物不是a黑猩猩),并且返回类型也错误(您需要back黑猩猩返回,但是得到一个
But you can't turn the example around, you can't assign a Bonobo => Animal
function where an Animal => Bonobo
function is expected, as the argument doesn't fit (it might get an animal that isn't a bonobo), and the return type is wrong either (you need a bonobo back, but get an animal, which could be something different).
对于所有类似函数的事物(例如方法)都是如此:参数类型是否更通用且无关紧要返回类型比预期的要特殊。 Contravariant和 covariant只是这个简单事实的幻想术语。
This is true for all function-like things (e.g. methods): It doesn't matter if argument types are more general and return types are be more special than expected. "Contravariant" and "covariant" is just fancy terminology for this simple fact.
这篇关于Scala:参数互变量和返回类型为何协变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!