0

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.

Lukas Cardot
  • 166
  • 1
  • 2
  • 12
  • Why do you assume java should be able to deduce the type? The argument type is `Function super T,? extends U>`. Java only has your argument to deduce that type, but there is no information. – Benjamin Maurer Jun 30 '20 at 09:30
  • 2
    `(MyClass m)` ← That is not a cast. – MC Emperor Jun 30 '20 at 09:32
  • @BenjaminMaurer If the type inference were cleverer, it could infer it from the type of the target, the variable. – Michael Jun 30 '20 at 09:37
  • @BenjaminMaurer Technically, it is possible to safely infer the type in this case. It's just that Java doesn't do it. Swift, for example, _can_ infer it. – Sweeper Jun 30 '20 at 09:38
  • @Michael well, if you look at the type of Comparator, you can compare a T and a U (e.g., String 'compare' MyClass). So even though Java looks at the return type, that doesn't help you in deducing the input type in this case. – Benjamin Maurer Jun 30 '20 at 10:01
  • @BenjaminMaurer The T in the parameter and the return are the same. So if you know the return should be `Comparator`, you can infer the parameters are MyClass and U. U can be inferred from the return of the `getId()` method. It is certainly possible to infer it, the compiler just is not that sophisticated. – Michael Jun 30 '20 at 12:06

0 Answers0