Lambda with non-stationary methods in Java 8

I am trying to learn lambdas in new Java 8. There is one interesting thing. If the method has the same signature as the functional interface, it can be assigned to it using the lambdas API. For example.

Comparator<Integer> myComp = Integer::compare; 

This method (Integer.compare) is static, takes two values, everything is perfect. the signature is the same as in the interface method. BUT this can be done using non-static methods, for example

 Comparator<Integer> myComp = Integer::compareTo. 

This method is non-static (instance level) and, in addition, it takes only one value. As I understand it, in Java there are no non-static methods, each method is static, but if it is not marked as static, this is required as the first parameter. Properly

 compareTo(this,Integer value). 

It would be reasonable to assume that the result will be undefined due to the comparison of the object and the integer. BUT IT IS WORK.

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

This works the same way. I have a debugged call method stack. When calling the comparator comparing method without instantiating this . The value is already initialized with the first parameter, and, of course, this is a valid object reference.

SO question: how does it work? When calling methods of the method compiler, if the class has only one field that has the same type as the first parameter in the method, if the class has a compiler, defiantly creates a new instance of the class with an initialized field or how does it work?

+9
java lambda java-8
Sep 11 '14 at 9:52
source share
1 answer

This is because lambdas are not from an object-oriented world.

When you assign a Comparator<Integer> a method, the task is to perform the comparison.

 Comparator<Integer> methodOne = Integer::compare; Comparator<Integer> methodTwo = Integer::compareTo; 

This methodOne.compare(1,2); will be translated to Integer.compare(1,2) , it is called a non-instance-capture and refers to a static method

This methodTwo.compare(1,2); will be translated into 1.compareTo(2) , called an instance call and refers to instance methods.

The compiler "knows" what type of method you referenced so that it can handle without errors.

Method Link Capture

+10
Sep 11 '14 at 11:18
source share



All Articles