8

Today I found strange code into jdk8 sources and couldn't find any explanation.

 static final Comparator<ChronoLocalDate> DATE_ORDER =
    (Comparator<ChronoLocalDate> & Serializable) (date1, date2) -> {
        return Long.compare(date1.toEpochDay(), date2.toEpochDay());
    };

Can anyone explain me why & Serializable out of <> ?
And it would be great to provide link on documentation.

Link to source: AbstractChronology

  • 3
    http://stackoverflow.com/questions/22807912/how-to-serialize-a-lambda : it is an intersection cast. – assylias Aug 04 '14 at 21:52
  • 1
    It’s worth noting that it is strongly discouraged to use serializable lambdas as the serialized form highly depends on the binary form of the containing class and even compiling with a different compiler (or a different version of it) might break compatibility. Especially in the example of this question, `DATE_ORDER` seems to be intended to be a singleton, a property the (de-)serialized lambda will not preserve. – Holger Aug 05 '14 at 09:03

2 Answers2

3

& in that context indicates an intersection of types. Say you have classes like these:

interface SomeInterface
{
  public boolean isOkay();
}

enum EnumOne implements SomeInterface { ... }

enum EnumTwo implements SomeInterface { ... }

You want to be able to use any enum that implements SomeInterface as a type parameter in a generic type. Of course, you want to be able to use methods on both Enum and SomeInterface, such as compareTo and isOkay, respectively. Here's how that could be done:

class SomeContainer<E extends Enum<E> & SomeInterface>
{
  SomeContainer(E e1, E e2)
  {
    boolean okay = e1.isOkay() && e2.isOkay();
    if (e1.compareTo(e2) != 0) { ... }
  }
}

See http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#4.9

Lucas Ross
  • 1,049
  • 8
  • 17
1

There are two parts to your question:

what is & Serializable?

It's a intersection of types - the type must be both Comparator<ChronoLocalDate> and Serializable

why is it not in angle brackets < >?

Because its a cast, not a generic parameter type

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
Bohemian
  • 412,405
  • 93
  • 575
  • 722