'How does Java method reference String::compareTo implementing Comparator<String> works?

java.util.Comparator<String> lambda = (s1, s2) -> s1.compareTo(s2); // line 1
java.util.Comparator<String> methodRef = String::compareTo;         // line 2

I can't understand why line 2 works without error, and why it is equivalent to line 1. Line 2 is returning a method reference that receives a string and returns and int (i.e. int compare(String s) ), however, comparator functional method signature is int compare(T o1, T o2);



Solution 1:[1]

The ref to String::compareTo is a special kind of method reference called "Reference to an Instance Method of an Arbitrary Object of a Particular Type".

In this case, the compiler knows that we are referencing a not-static method of a given class, and it can translate to a functional interface with the desired signature.

For example:

String t1 = "t1";
String t2 = "t2";

// this
Comparator<String> comparator = String::compareTo;
comparator.compareTo(t1, t2);

// will be 'translated' to:
Comparator<String> comparator = (String s1, String s2) -> s1.compareTo(s2);
t1.compareTo(t2);

Note that the method will be called with the context of the first parameter (the this used will be t1).

Points 8 and 9 of State of lambda give a rationale for this implementation.

From Overview of method references youtube video

Overview of method references

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Hofmann