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

后端 未结 4 1255
抹茶落季
抹茶落季 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:50

    I remember being confused by that very sentence when I was reading the Scala Book back in 2007. Martin delivers it as if he was talking about a language feature, but in that sentence he only states a fact about functions in general. Scala, specifically, models that fact simply by a regular trait. Since Scala has declaration-site variance, expressing those semantics is natural to the language.

    Java Generics, on the other hand, support only use-site variance, so the closest one can get to co/contravariance of a function type in Java is to hand-code it at each use site:

    public int secondOrderFunction(Function fn) {
         ....
    }
    

    (assuming an appropriately declared interface Function, P standing for parameter type and R for return type). Naturally, since this code is in the hands of the client, and not being specific to functions at all, the statement about param type/return type variance is not applicable to any language feature of Java. It is only applicable in a broader sense, pertaining to the nature of functions.

    Java 8 will introduce closures, which implies first-class functions, but, as per Jörg's comment below, the implementation will not include a fully-fledged function type.

提交回复
热议问题