Isn't the argument type co- not contra-variant?

后端 未结 4 1252
抹茶落季
抹茶落季 2020-12-03 05:12

I understand the terms co-variance and contra-variance. But there is one small thing I am unable to understand. In the course \"Functional Programming in Scala\" on coursera

4条回答
  •  鱼传尺愫
    2020-12-03 05:54

    This is how functions are defined in Scala:

    trait Function1 [-T1, +R]  extends AnyRef
    

    In English, parameter T1 is contravariant and result type R is covariant. What does it mean?

    When some piece of code requires a function of Dog => Animal type, you can supply a function of Animal => Animal type, thanks to contravariance of parameter (you can use broader type).

    Also you can supply function of Dog => Dog type, thanks to covariance of result type (you can use narrower type).

    This actually makes sense: someone wants a function to transform dog to any animal. You can supply a function that transforms any animal (including dogs). Also your function can return only dogs, but dogs are still animals.

提交回复
热议问题