Narrow the return type of Comparator.{thenComparing,reverseOrder}

Michael Hixson michael.hixson at gmail.com
Thu Jan 31 20:26:06 PST 2013


The following code does not compile:

  Comparator<CharSequence> c = Comparators.comparing(
      (ToIntFunction<CharSequence>) CharSequence::length);
  Comparator<String> d = c.reverseOrder();
  Comparator<String> e = c.thenComparing(
      (ToIntFunction<String>) String::hash32);

(The errors are on the lines that assign to d and e.)

I believe these would be fine if the signatures of thenComparing and
reverseOrder were modified slightly:

  default <S extends T> Comparator<S> reverseOrder();

  default <S extends T> Comparator<S> thenComparing(
      Comparator<? super S> other);

  default <S extends T, U extends Comparable<? super U>> Comparator<S>
  thenComparing(Function<? super S, ? extends U> keyExtractor);

  default <S extends T> Comparator<S> thenComparing(
      ToIntFunction<? super S> keyExtractor);

  default <S extends T> Comparator<S> thenComparing(
      ToLongFunction<? super S> keyExtractor);

  default <S extends T> Comparator<S> thenComparing(
      ToDoubleFunction<? super S> keyExtractor);

If there's a downside to this change, I don't know of it.  Is there one?

-Michael


More information about the lambda-libs-spec-comments mailing list