2017-10-16 36 views
3

我前幾天寫了一個函數,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; 
    } 

} 
+0

它是從intelliJ錯誤還是它實際編譯,你可以測試? – Lino

+0

它編譯,它只是一個有用的提示:我看到你正在使用lambda,你想使用Testcase :: withString嗎? – Jani

回答

3

public Testcase withString(String string)方法有兩個參數:第一個是隱式的 - 在Testcase實例上調用該方法,第二個是明確的 - 一個String說法。

因此方法參考Testcase::withString可分配給WithFunction<Testcase, String>類型的變量。

當您撥打withFunction.apply(new Testcase(), "string")時,將創建一個Testcase實例,並將String「字符串」傳遞給該實例的withString(String string)方法。

+0

是的,我認爲那是發生了什麼,但是你知道這個隱式連接在哪裏嗎?它有什麼文件嗎?這是非常有用的,所以我想知道是否還有其他這種隱含的聯繫,我可以做,並簡化其他的事情。 – Jani

+1

@Jani您可以閱讀有關方法參考的任何文檔。對非靜態方法的方法引用有一個隱含的第一個參數,它是調用該方法的實例。就是這樣。 – Eran

相關問題