9

I was looking into the source code of Comparator#comparing() from JDK 1.8, and the casting of lambda was a surprise for me:

//declaration
{
    Objects.requireNonNull(keyExtractor);
    return (Comparator<T> & Serializable)  // <- this cast here
        (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
}

After reading that

The returned comparator is serializable if the specified function is also serializable.

and some playing with the code, I figured out why this works and why it wouldn't work if the cast was different.

My question is: What is this (A & B) multiple casting?

By googling java multiple cast I found only multiple casting using (A)(B). Is there like an article about adding this in JDK 1.8?

kajacx
  • 12,361
  • 5
  • 43
  • 70
  • It's been there since 1.5, it's just not used very often. – yshavit Aug 17 '14 at 22:05
  • I meant if the `(A)(B)` cast was used or if the cast wasn't there at all. – kajacx Aug 17 '14 at 22:06
  • @yshavit: interesting, my Eclipse 4.4 says `Additional bounds are not allowed in cast operator at source levels below 1.8` if i change the jdk version to 1.7 (But Eclipse could be wrong of course) – kajacx Aug 17 '14 at 22:08
  • 2
    For the cast with &, I found that: http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.16 and the diff with 1.7: http://docs.oracle.com/javase/specs/jls/se8/jls8-diffs.pdf and from this one, it seems it was already there in 1.7. But I don't understand the usage here ? – NoDataFound Aug 17 '14 at 22:11
  • From your "1.7" diff: `Specification: JSR-337 Java® SE 8 Release Contents` (2nd page, also `se8` in URL). Moreover there is nothing babout this in the [1.7 version](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.16). But thanks a lot, this is exacly what i wanted. – kajacx Aug 17 '14 at 22:23
  • 9
    Intersection bounds have been permitted in *type variable bounds* since generics were introduced. Java 8 extended this to functional interface target types for lambdas and method references. – Brian Goetz Aug 18 '14 at 01:10

0 Answers0