问题描述
我知道在标准库中使用 co-
和 contravariance
(例如,集合和特征 Function
)我想知道 co-
和 contravariance
如何在真实世界的业务应用程序。
I know about using co-
and contravariance
in the standard library (e.g. collections and trait Function
) I wonder how co-
and contravariance
are used in design of "real world" business applications.
推荐答案
经典示例是函数,将Scala接口用于具有单个参数的函数:
The classic example is functions, taking the Scala interface for a function with a single argument:
trait Function1[-T1, +R]
对于该参数而言是逆变的(-
),对于参数而言是协变的( +
)返回类型。
Which is contravariant (the -
) for the argument, and covariant (the +
) for the return type.
为什么?
想象一下您有以下这些类:
Imagine you have these classes:
class Timelord { ... }
class Doctor extends Timelord { ... }
class Enemy { ... }
class Dalek extends Enemy { ... }
如果您有采取的方法,作为参数, Doctor =>敌人
函数;那么可以提供 TimeLord =>的实例敌人
。它仍然会接受 Doctor
的实例。
If you have a method that takes, as a parameter, a Doctor => Enemy
function; then it's okay to supply an instance of TimeLord => Enemy
. It'll still accept instances of Doctor
.
所以 TimeLord =>敌人
是 Doctor =>的子类。敌人
,因为 TimeLord
是 Doctor
的超类,它是
So TimeLord => Enemy
is a subclass of Doctor => Enemy
because TimeLord
is a superclass of Doctor
, it's contravariant in that parameter.
同样,返回 Dalek
的函数在以下情况下有效您需要一个返回 Enemy
的函数,因为 Dalek
是- Enemy
Likewise, a function returning a Dalek
is valid when you need a function returning some Enemy
, because a Dalek
is-an Enemy
所以 Doctor => Dalek
是 Doctor =>的子类。敌人
是因为 Dalek
是 Enemy
的子类,该参数中的协变量。
So Doctor => Dalek
is a subclass of Doctor => Enemy
because Dalek
is a subclass of Enemy
, it's covariant in that parameter.
这篇关于在设计业务应用程序时如何使用协方差和反方差?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!