前几天我写了一个函数,Intellij告诉我我可以简化它。我有一个带有一个方法的函数接口,这个方法有两个参数。它的返回类型与第一个输入参数相同。
事实证明,我可以向一个只需要一个参数(最后一个参数)的方法发送一个引用,只要它返回正确的类型。我尝试在函数接口中更改Type1和Type2参数的顺序,但这不起作用。我认为这是行不通的。有人能解释一下它的工作原理或链接到我的文档吗?我找不到任何信息。
工作示例
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;
}
}发布于 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)方法。
https://stackoverflow.com/questions/46769429
复制相似问题