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

2
  • 3
    stackoverflow.com/questions/22807912/how-to-serialize-a-lambda : it is an intersection cast. Commented Aug 4, 2014 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. Commented Aug 5, 2014 at 9:03

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.