4

Looking at java.util.Comparator in the JDK 8 source code, I found interesting code:

public static <T, U extends Comparable<? super U>> Comparator<T> comparing(Function<? super T, ? extends U> keyExtractor){
        Objects.requireNonNull(keyExtractor);
        // casting to Serializable?
        return (Comparator<T> & Serializable)
            (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
    }

It is pretty clear why we are casting the resulting lambda to Comparator<T>, but what is the purpose of casting it to Serializable?

slim
  • 40,215
  • 13
  • 94
  • 127
Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
  • Related: http://stackoverflow.com/questions/22807912/how-to-serialize-a-lambda -- and note how Oracle "strongly discourage" the practice: https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#serialization -- where have you found this code? – slim Mar 22 '17 at 17:05
  • 2
    @slim the code is from `java.util.Comparator` – Eugene Mar 22 '17 at 17:27
  • Interesting. My guess is that unless they do this, nobody could make *any* class serializable if it contained a comparator (or they'd have to put in extra effort). But I've never made much use of `serialize()` so will wait to see a more authoritative answer. – slim Mar 22 '17 at 17:36
  • http://stackoverflow.com/questions/41500021/why-does-java-8s-comparator-comparing-cast-the-return-value-to-serializable – Alexis C. Mar 22 '17 at 19:29

1 Answers1

3

That is making the lambda serializable from what I know.

Eugene
  • 117,005
  • 15
  • 201
  • 306