Contravariance explained

前端 未结 5 1522
梦如初夏
梦如初夏 2020-11-27 11:57

First of, I have read many explanations on SO and blogs about covariance and contravariance and a big thanks goes out to Eric Lippert for producing such a great series on Co

5条回答
  •  失恋的感觉
    2020-11-27 12:26

    Look at it this way: If I have a function func that deals with Subtype Mammal, of the form Mammal m = Func(g(Mammal)), I can swap out Mammal with something that encompasses Mammal, which here is the Base Animal.

    In terms of a sporting analogy to understand the below image, you can catch a ball with your bare hands like in Cricket, but it's also possible (and easier) to catch a ball using Baseball gloves.

    What you see on the left is covariance, what you see inside the parameter part is contravariance.

    You may wonder "Why is the left green curve bigger than the red curve? Isn't the Subtype which usually does more than the basetype supposed to be bigger?" Answer: No. The size of the bracket denotes the variety of objects allowed, like a Venn diagram. A Set of Mammal is smaller than Set Animal. Similarly, f(Mammal) is smaller than f(Animal) as it only supports a smaller set of objects. (i.e a function that handles Mammals won't handle all Animals, but a function that handles Animals can always handle a Mammal). Hence, the relationship is inverted as f(animal) can be passed in instead of f(mammal) thereby making it contravariant.

提交回复
热议问题