首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java函数接口匹配具有较少输入参数的方法

Java函数接口匹配具有较少输入参数的方法
EN

Stack Overflow用户
提问于 2017-10-16 19:38:13
回答 1查看 56关注 0票数 3

前几天我写了一个函数,Intellij告诉我我可以简化它。我有一个带有一个方法的函数接口,这个方法有两个参数。它的返回类型与第一个输入参数相同。

事实证明,我可以向一个只需要一个参数(最后一个参数)的方法发送一个引用,只要它返回正确的类型。我尝试在函数接口中更改Type1和Type2参数的顺序,但这不起作用。我认为这是行不通的。有人能解释一下它的工作原理或链接到我的文档吗?我找不到任何信息。

工作示例

代码语言:javascript
复制
public class Testcase {

    private String string;

    @FunctionalInterface
    interface WithFunction<Type1, Type2> {
        Type1 apply(Type1 type1, Type2 type2);
    }

    public static void main(String[] args) {
        WithFunction<Testcase, String> withFunction = Testcase::withString;
        Testcase testcase = withFunction.apply(new Testcase(), "string");
        System.out.println(testcase.string);
    }

    public Testcase withString(String string) {
        this.string = string;
        return this;
    }

}
EN

回答 1

Stack Overflow用户

发布于 2017-10-16 19:50:57

public Testcase withString(String string)方法有两个参数:第一个是隐式的-在其上调用该方法的Testcase实例,第二个是显式的-一个String参数。

因此,可以将方法引用Testcase::withString赋值给WithFunction<Testcase, String>类型的变量。

当您调用withFunction.apply(new Testcase(), "string")时,将创建一个Testcase实例,并将String "string“传递给该实例的withString(String string)方法。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46769429

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档