Hello.

Here I started picking lambda in new java. There is one interesting thing. You can assign a method to a functional interface if the signature matches the interface method. Let's say

Comparator<Integer> myComp = Integer::compare;

This method is static, takes two parameters to the input, everything is fine. But you can do this with non-static method. Let's say

Comparator<Integer> myComp = Integer::compareTo .

This method is non-static, moreover, it takes only 1 parameter. As I understand it, all the methods in Java are static, simply if the method is non-static, then an additional parameter this is passed to it, indicating the object instance. That is, it is actually transmitted as follows:

compareTo(this,Integer value) .

It was logical to assume that the result will be unknown what. Since we are going to compare the object with int.
But still everything works fine.

 Comparator<Integer> comparator = Integer::compareTo; Comparator<Integer> comparator2 = Integer::compare; System.out.println(comparator.compare(1,2)); System.out.println(comparator2.compare(1,2)); 

Here it works the same way.

Prodabazhil in the course of method calls.

When calling the compare method of the comparator, that is, without creating an instance, this.value already contains the number passed by the first parameter and, accordingly, the class object created.
Actually, the question itself: how does it all work? When calling, the compiler looks for a class to have a single field that matches the method argument, and if it does, creates an implicit class object, initializing the field with the first argument? Or how does it work?
Thank you in advance.

    1 answer 1

    This lambda application has 3 options:

    object :: instanceMethod - we pass the method of the specified object, with matching parameters;

    Сlass :: staticMethod - we transfer the static method of the specified class with the correspondence by parameters;

    Class :: instanceMethod - the specified class method is passed.

    We do not consider the option of passing a reference to a constructor method. Our case is the third one just in this list, and it has a simple trick: the first parameter becomes the target object of the method, that is, the link this.

    If you deploy your

     Comparator<Integer> comparator = Integer::compareTo; 

    then we get

     Comparator<Integer> comparator = (x,y) -> x.compareTo(y); 

    And everything falls into place.

    Here (English documentation) and here (in Russian) - more detailed information.