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

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

问题描述

我被下面的代码弄糊涂了

I am confused by the following code

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 的分配会失败,因为我的消耗方法与消费者接口中的接受方法不匹配 - 返回类型不同,字符串与无效.

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 - 它返回一个值的事实是无关紧要的,因为 - 在这种情况下 - 它被简单地忽略了.(因为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) 这样的方法都会返回一个值:boolean.仅仅因为它们返回某些东西(这在许多情况下几乎不相关)而无法传递这些方法引用会很烦人.

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天全站免登陆