Search code examples
javajava-8method-referencefunctional-interface

Why Method reference is compatible to a functional interface with difference number of args?


I understand that method reference can be used to implement a functional interface if the referred method takes the same number of args as the functional interface and return the same type, but why in some cases the referred method has different number of args than the functional interface but are still compatible?

I have a simple BiConsumer that I try to use method reference to implement it. I know I can use lambda expression also as long as the number of args matches. I will show the code to explain it clearly.

I have a BiConsumer<ArrayList<String>, ? super String> that I want to implement.

Lambda expression way to do that is:

BiConsumer<ArrayList<String>, ? super String> b = (firstArg,secondArg) -> firstArg.add(secondArg); since they both takes 2 input args, there is no problem.

But why BiConsumer<ArrayList<String>, ? super String> a = ArrayList::add; is also compatible? The add method on ArrayList only takes 1 input args but the functional interface needs 2.

Any answers would be greatly appreciated. Thanks!


Solution

  • 15.12.2.1. Identify Potentially Applicable Methods

    A method reference expression (§15.13) is potentially compatible with a functional interface type T if, where the arity of the function type of T is n, there exists at least one potentially applicable method when the method reference expression targets the function type with arity n (§15.13.1), and one of the following is true:

    • The method reference expression has the form ReferenceType :: [TypeArguments] Identifier and at least one potentially applicable method is either (i) static and supports arity n, or (ii) not static and supports arity n-1.

    The function type you want to use has arity 2

    void accept(T t, U u);
    

    and the method ArrayList::add refers to has arity 1, and it's not static. It makes it potentially applicable.