1

Can someone please explain why inlining evensFirst causes compilation to fail?

import java.util.Comparator;

public class Main
{
    public static void main(String[] args) {
        Comparator<Integer> evensFirst = Comparator.comparingInt(t -> t%2);
        Comparator<Integer> oddsFirst = evensFirst.reversed();

        // Inlining evensFirst causes compilation to fail with
        // "The operator % is undefined for the argument type(s) Object, int"
        Comparator<Integer> oddsFirst2 = Comparator.comparingInt(t -> t%2).reversed();
    }
}
  • I assume it's something related to generics and type inference, but what is the explanation?
  • And how can I have the code inline?
jsiqueira
  • 173
  • 1
  • 9
  • 1
    It is telling you the exact error: `t` is an `Object` whereas 2 is a primitive `int`, and `%` is not applicable in that case. Probably you need not to use `%` and `2`... – nbro Feb 02 '16 at 14:42
  • @nbro The question is likely asking why the 2 first lines in main() works fine, while combining those 2 lines into the last line in main() gives an error. Though it would help a lot if this was made clear in the question, so people don't have to guess. – nos Feb 02 '16 at 14:46
  • 2
    This is a type-inference issue that goes a lot deeper that you imagine... Read the linked question that was answered by a JDK developer. See also [this question](http://stackoverflow.com/q/24794924/1743880). – Tunaki Feb 02 '16 at 14:49
  • @Tunaki Thanks for the link. To answer my second question, all I needed to do was add a type witness, as such: `Comparator oddsFirst2 = Comparator.comparingInt(t -> t%2).reversed();` – jsiqueira Feb 02 '16 at 14:55
  • @jsiqueira Yes, this works because you explicitely specify the type. – Tunaki Feb 02 '16 at 14:56

0 Answers0