方法参考,协方差 [英] method reference, covariance contravariance

查看:66
本文介绍了方法参考,协方差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚发现java 8允许引用具有更特定的返回类型和更通用的参数的方法.

I just discovered that java 8 allows to reference a method with more specific return type and more general parameters.

import java.util.function.Function;

public class MethodReferences {
    public static Integer function(Object o) {
        return 2;
    }

    public static void main(String[] args) {
        Function<String, Object> function = MethodReferences::function;
    }
}

这非常灵活.

但是为什么他们不将其扩展到其他情况呢?

But why they didn't extend this to other cases ?

例如:

import java.util.function.Function;

public class Main {


    public static void main(String[] args) {
        Function<String, Object> function = function();
    }

    private static Function<Object, Integer> function() {
        return new Function<Object, Integer>() {

            @Override
            public Integer apply(Object o) {
                return 1;
            }
        };
    }
}

编译失败:

Type mismatch: cannot convert from Function<Object,Integer> to Function<String,Object>

推荐答案

这是泛型的简单限制.类型系统不知道ObjectInteger中的哪一个是返回类型和参数类型,因此它不具有任何协方差/相反方差的灵巧性.

That's a simple limitation of generics. The type system doesn't know which of Object and Integer are return types and argument types, so it can't do any covariance/contravariance smartness.

如果要表达使用X的超类型并返回Y的子类型的函数" ,请执行Function<? super X, ? extends Y>.确实,如果您进行更改

If you want to express "A function that takes a supertype of X and returns a subtype of Y" you do Function<? super X, ? extends Y>. And indeed, if you change

Function<String, Object> function = function();

Function<? super String, ? extends Object> function = function();

您的代码会编译. (? extends Object?相同,但为清楚起见,我将其写出了

your code compiles. (? extends Object is identical to ? but I wrote it out for clarity)

这篇关于方法参考,协方差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆