So I have a class:
class MyClass {
String id;
String name;
// getter/setter/constructor omitted
}
and a working Comparator:
Comparator<MyClass> myComparator = Comparator
.comparing(MyClass::getName)
.thenComparing(MyClass::getId)
Everything is ok until then, but I was wondering why by changing the Comparator as shown below we get a compilation error at comparing
:
Comparator<MyClass> myComparator = Comparator
// m is infered to Object
.comparing(m -> m.getId())
.thenComparing(MyClass::getName);
It is in my understanding that m
should be inferred to MyClass
, but it does not seem like it. We need to explicitly cast the lambda parameter:
Comparator<MyClass> myComparator = Comparator
.comparing((MyClass m) -> m.getId())
.thenComparing(MyClass::getName);
N.B.: Tested with JDK 11 and 14.