From JDK8's Comparator.java:
public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
Function<? super T, ? extends U> keyExtractor)
{
Objects.requireNonNull(keyExtractor);
return (Comparator<T> & Serializable)
(c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
}
Notice the return statement is prefixed with an interesting cast: (Comparator<T> & Serializable)
I am already aware of and (I think) understand:
- the
&
operator in generic type restrictions (and can infer its purpose here), - the
Serializable
interface.
However, used together in the cast is baffling to me.
What is the purpose of & Serializable
if the return type does not require it?
I do not understand the intent.
Follow-up to dupe/close requests: This question How to serialize a lambda? does not answer question. My question specifically notes the return type has no mention of Serializable
, thus the source of my confusion.
Serializable
makes it serializable. This method casts to allow callers to serialize the result if they so choose. – Gathers