Reputation: 5775
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);
Upvotes: 1
Views: 264
Reputation: 3627
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
Upvotes: 5