简体   繁体   中英

Cannot infer type argument of Comparator when not using a local variable

I have a weird compiler error while trying to use the Comparator comparing and thenComparing methods to chain comparators together. I have a list of tuples and I want to sort the list first by the first element of all tuples, and in case of duplicates I want to sort by the second element.

In the first attempt I construct the comparator in stages. The comparison of the first element of the tuples is referenced by the local variable c1. Then the second element comparator is constructed from that variable.

In the second attempt I inline the construction of the first element comparator and go without any local variables. I would assume the code is identical to the previous attempt but suddenly the compiler flags the code up as a compile-time error.

public class Example {
    
    public static class Tuple<A, B> {
        
        private final A a;
        private final B b;
        
        public Tuple(A a, B b) {
            this.a = a;
            this.b = b;
        }
        
        public A getA() {return a;}
        
        public B getB() {return b;}
        
    }
    
    {
        List<Tuple<Integer, String>> tuples = new ArrayList<>();
        
        Comparator<Tuple<Integer, String>> c1 = Comparator.comparing(Tuple::getA);
        
        // Attemp 1) compiles
        tuples.sort(c1.thenComparing(Comparator.comparing(Tuple::getB)));
        
        // Attemp 2) does not compile.
        // compiler error: Cannot infer type argument(s) for <T, U> comparing(Function<? super T,? extends U>)
        tuples.sort(Comparator.comparing(Tuple::getA).thenComparing(Comparator.comparing(Tuple::getB)));
        //          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    }
    
    
}

Am I missing something super simple here? An inlining like this should never lead to a compile-time error in my opinion. Could this be a compiler bug? I am using the JDK 14 preview after all. Would be nice to know if others have this issue as well with older JDK versions.

As chrylis -cautiouslyoptimistic- has pointed out in a comment this is indeed a problem with the IDE that I am using (in this case I was using Eclipse 2020-06 (4.16.0)) rather than the Java Compiler. When I compile the file using the command line it works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM