I wrote some simple code like below. This class works fine without any errors.
public class Test {
public static void main(String[] args) {
List&
First trick: all instance methods actually take 1 additional implicit argument, the one you refer to as this in method body. E.g.:
public final class Integer extends Number implements Comparable {
public int compareTo(/* Integer this, */ Integer anotherInteger) {
return compare(this.value, anotherInteger.value);
}
}
Integer a = 10, b = 100;
int compareResult = a.compareTo(b);
// this actually 'compiles' to Integer#compareTo(this = a, anotherInteger = b)
Second trick: Java compiler can "transform" the signature of a method reference to some functional interface, if the number and types of arguments (including this) satisfy:
interface MyInterface {
int foo(Integer bar, Integer baz);
}
Integer a = 100, b = 1000;
int result1 = ((Comparator) Integer::compareTo).compare(a, b);
int result2 = ((BiFunction) Integer::compareTo).apply(a, b);
int result3 = ((MyInterface) Integer::compareTo).foo(a, b);
// result1 == result2 == result3
As you can see class Integer implements none of Comparator, BiFunction or a random MyInterface, but that doesn't stop you from casting the Integer::compareTo method reference as those interfaces.