最近在读lambda表达式相关的java源码,在Comparator的静态方法里发现有不少这种类似的写法
java.util.Comparator
…
public static Comparator comparingInt(ToIntFunction<? super T> keyExtractor) {
Objects.requireNonNull(keyExtractor);
return (Comparator & Serializable)
(c1, c2) -> Integer.compare(keyExtractor.applyAsInt(c1), keyExtractor.applyAsInt(c2));
}
其中return (Comparator & Serializable)应该是表示类型强转
The part I’m interested in is this: return (Comparator & Serializable):
This means that the resulting value will be cast to Comparator and Serializable (i.e. a serializable comparator)
Note that when doing casts like this one, you’re allowed to specify only one class (and infinite amount of interfaces), because it’s not possible for a class to inherit from more than one super-class.