When should use covariance and contravariance when designing a class with generic type

Viewed 394

I'm learning functional programming and I'm trying to understand covariance and contravariance concept. My problem now is: I don't really know when should apply covariance and contravariance to a generic type. In specific example, yes, I can determine. But in general case, I don't know which general rule.

For example here is some rules that I have studied:

  • if generic type acts as parameter: using contravariance. (1)
  • if generic type acts as retrun value: using covariance. (2)

In some languages that I known while stuyding this concept also use those convention. For example: in keyword for covariance(In Scala is +) and out keyword for contravariance (in Scala is -). Point (1) is easy to understand. But at point (2), I see exception:

  • methodA(Iterator<A>) A should be covariance
  • methodA(Comparator<A>) A should be contravariance.

So the exception here is: although both 2 cases using generic type as input but one should be covariance and other should be contravariance. My question is: do we have any general rule to decide covariance/contravariance when designing a class.

Thanks

1 Answers
Related