我前幾天寫了一個函數,Intellij告訴我可以簡化。我有一個方法的功能接口,有2個參數。它的返回類型與第一個輸入參數相同。Java Functional Interface與輸入參數較少的方法相匹配
原來,只要它返回正確的類型,我就可以向一個只需要一個參數(最後一個參數)的方法發送一個參考。我嘗試在功能接口中切換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;
}
}
它是從intelliJ錯誤還是它實際編譯,你可以測試? – Lino
它編譯,它只是一個有用的提示:我看到你正在使用lambda,你想使用Testcase :: withString嗎? – Jani