Why is BiConsumer allowed to assign using a function that accepts only one parameter?

Let's say in the following example:

public class MyConsumer {
    public void accept(int i) {}
    public static void biAccept(MyConsumer mc, int i) {}
}

public class BiConsumerDemo {

    public void accept(int i) { }
    public static void biAccept(MyConsumer mc, int i) { }

    private void testBiConsume() {
        BiConsumer<MyConsumer, Integer> accumulator = (x, y) -> {}; // no problem, method accepts 2 parameters
        accumulator = MyConsumer::accept; // accepts only one parameter and yet is treated as BiConsumer
        accumulator = MyConsumer::biAccept; // needed to be static
        accumulator = BiConsumerDemo::accept; // compilation error, only accepts single parameter
    }
}

Why is a variable accumulatorthat is BiConsumer, which requires a function to accept 2 parameters, can be assigned with MyConsumer::acceptwhen this method accepts only one parameter?

What is the principle of this language in Java? If there is a term for it, what is it?

+4
source share
1 answer

MyConsumer::acceptis a reference to an instance method of a class MyConsumerthat has a single type argument int. The instance MyConsumeron which the method is called is considered the implicit argument of the method reference.

In this way:

accumulator = MyConsumer::accept;

is equivalent to:

accumulator = (MyConsumer m,Integer i) -> m.accept(i);

n , :

  • ReferenceType:: [TypeArguments] , - , ( ), , arity (n n-1) arity ( [TypeArguments]), §15.12.2.1.

    : n n-1, , .

( 15.13.1. )

BiConsumer, 2 . MyConsumer, accept 2 1 .

, 2 , 1 , .

+4

Source: https://habr.com/ru/post/1693794/


All Articles