I have the following class:
public class Car {
private float enginePower;
private float wheelDiameter;
public float getEnginePower() {
return enginePower;
}
static final Comparator<Car> simpleCarComparator = Comparator.comparing(c -> c.enginePower);
static final Comparator<Car> advancedCarComparator = simpleCarComparator.thenComparing(c -> c.wheelDiameter);
// Does not work
static final Comparator<Car> bothInOneCarComparator = Comparator.comparing(c -> c.enginePower).thenComparing(c -> c.wheelDiameter);
}
The last Comparator does not compile, because the Compiler thinks the lambdas are Function<Object,?>
leaving c
without an enginePower
member. I know I can easily fix this, by either casting (Car c) -> c.enginePower
or using a method reference Car::getEnginePower
, then the compiler can infer the type for both lambdas.
However I would like to understand why the compiler cannot simply infer the type and figure out by itself that c
is a Car
. While c
could be any superclass of Car
to make the assignment legal, only Car
itself makes sense here and for the simpleCarComparator
the Compiler also infered that c
is a Car
and not just Object
.