I'm using Comparator
s to sort streams and I've come across a compiler error that I don't understand.
Let's say I have the following classes:
class Base {
private LocalDate date;
public LocalDate getDate() { return date; }
...
}
class Sub extends Base { ... }
I'm creating two comparators to sort Sub
s by their date, one by the natural order and one in the reverse order. The following code compiles:
Comparator<Sub> fwd = Comparator.comparing(Sub::getStartDate);
Comparator<Sub> rev1 = Comparator.comparing(Sub::getStartDate).reversed();
Comparator<Sub> rev2 = fwd.reversed();
Realising that getDate()
is defined on Base
, I thought I'd try the following:
Comparator<Sub> fwd = Comparator.comparing(Base::getStartDate);
Comparator<Sub> rev1 = Comparator.comparing(Base::getStartDate).reversed(); // Compiler error
Comparator<Sub> rev2 = fwd.reversed(); // OK
Surprisingly (to me), the code for rev2
compiles okay, while the code for rev1
produces the following errors:
Cannot infer type argument(s) for <T, U> comparing(Function<? super T, ? extends U>)
The type Base does not define getStartDate(Object) that is applicable here
Why do I get these compiler errors? And why can I effectively circumvent them when building rev2
from fwd
?
(I'm using Eclipse Oxygen.3a (4.7.3) and Java v1.8.0_162 if that's relevant.)