为什么返回类型的Java方法引用与Consumer接口匹配? [英] Why does a Java method reference with return type match the Consumer interface?

查看:159
本文介绍了为什么返回类型的Java方法引用与Consumer接口匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对以下代码感到困惑

class LambdaTest {
    public static void main(String[] args) {
        Consumer<String>         lambda1 = s -> {};
        Function<String, String> lambda2 = s -> s;

        Consumer<String>         lambda3 = LambdaTest::consume; // but s -> s doesn't work!
        Function<String, String> lambda4 = LambdaTest::consume;
    }

    static String consume(String s) { return s;}
}

我原本期望lambda3的赋值失败,因为我的consume方法与Consumer Interface中的accept方法不匹配 - 返回类型不同,String vs void。

I would have expected the assignment of lambda3 to fail as my consume method does not match the accept method in the Consumer Interface - the return types are different, String vs. void.

此外,我一直认为Lambda表达式和方法引用之间存在一对一的关系,但显然并非如我的示例所示。

Moreover, I always thought that there is a one-to-one relationship between Lambda expressions and method references but this is clearly not the case as my example shows.

有人能向我解释这里发生了什么?

Could somebody explain to me what is happening here?

推荐答案

consume(String)方法匹配 Consumer< String> interface,因为它消耗 String - 它返回一个值的事实是无关紧要的,因为 - 在这种情况下 - 它被简单地忽略了。 (因为 Consumer 界面根本不期望任何返回值。)

consume(String) method matches Consumer<String> interface, because it consumes a String - the fact that it returns a value is irrelevant, as - in this case - it is simply ignored. (Because the Consumer interface does not expect any return value at all).

它一定是设计选择基本上是一个实用程序:想象有多少方法需要重构或重复以匹配功能接口的需求,如 Consumer ,甚至是非常常见的 Runnable 。 (请注意,您可以将任何不使用参数的方法作为 Runnable 传递给 Executor 。)

It must have been a design choice and basically a utility: imagine how many methods would have to be refactored or duplicated to match needs of functional interfaces like Consumer or even the very common Runnable. (Note that you can pass any method that consumes no parameters as a Runnable to an Executor, for example.)

即使像 java.util.List#add(Object)这样的方法也会返回一个值:布尔。由于他们返回某些东西(在很多情况下几乎不相关)而无法传递此类方法引用会相当烦人。

Even methods like java.util.List#add(Object) return a value: boolean. Being unable to pass such method references just because that they return something (that is mostly irrelevant in many cases) would be rather annoying.

这篇关于为什么返回类型的Java方法引用与Consumer接口匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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