public class Car {
private int maxSpeed;
public Car(int maxSpeed) {
this.maxSpeed = maxSpeed;
}
public int getMaxSpeed() {
return maxS
The assignment:
Function function = carX::getMaxSpeed;
does not compile because it's a Supplier, not a Function.
So then, why does this compile?:
Comparator.comparing(Car::getMaxSpeed)
Java 8 allows an instance method reference that is a Supplier to be provided where a Function is expected, and the compiler effectively converts the getter method into a function.
To find out why this is possible, let's look at how we invoke a getter method using reflection:
System.out.println(Car.class.getMethod("getMaxSpeed").invoke(carX)); // "155"
When calling invoke() on an instance method, we pass the instance to the invoke() method of the getter's Method - there's an implied parameter of the instance type. When looked at it this way, we see that under the hood a getter is really implemented as a Function via the invoke() method.