Scala:参数互变量和返回类型为何协变量? [英] Scala: arguments contravariant and return types are covariant why?

查看:87
本文介绍了Scala:参数互变量和返回类型为何协变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 type Bonobo of bar, 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 type Animal of bar, hence covariant), but this is fine, as the caller of bar 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆