所以我有一堂课:
class MyClass {
String id;
String name;
// getter/setter/constructor omitted
}
和有效的比较器:
Comparator<MyClass> myComparator = Comparator
.comparing(MyClass::getName)
.thenComparing(MyClass::getId)
到那时一切都还可以,但是我想知道为什么通过如下所示更改Comparator会在comparing
处出现编译错误:
Comparator<MyClass> myComparator = Comparator
// m is infered to Object
.comparing(m -> m.getId())
.thenComparing(MyClass::getName);
据我了解,应该将m
推论为MyClass
,但似乎并非如此。我们需要显式转换lambda参数:
Comparator<MyClass> myComparator = Comparator
.comparing((MyClass m) -> m.getId())
.thenComparing(MyClass::getName);
N.B .:已通过JDK 11和14测试。