skiwi
skiwi

Reputation: 69379

What is the type of an intersected type?

Consider the following code which uses the ability to intersect types, which was added in Java 8:

private <E, T extends List<E> & RandomAccess> void takeList(T list) {

}

private void fakingRandomAccess() {
    List<Integer> linkedList = new LinkedList<>();
    takeList((List<Integer> & RandomAccess)linkedList);
}

I have made a takeList method that only takes lists that have (near) constant access times, for whatever reason, but I can imagine that there would be situations where it is indeed warranted to do it such.

Passing an ArrayList<E> into the method should work just fine, however via type intersections you can also pass in a LinkedList<E> by pretending that it has constant access time.

Now my questions are:

Upvotes: 8

Views: 1798

Answers (1)

Holger
Holger

Reputation: 298469

You are mixing two different things up.

In the How to serialize a lambda? question & answer there is a lambda expression being cast to an intersection type.

Runnable r = (Runnable & Serializable)() -> System.out.println("Serializable!");

This tells the compiler to generate a type compatible to the intersection type. Therefore the generated class for the lambda expression will be both, Runnable and Serializable.


Here you are casting an instance of a concrete class to an intersection type:

(List<Integer> & RandomAccess)linkedList

This requests a runtime-check whether the concrete instance’s class implements an appropriate type, i.e. fulfills all interfaces. This runtime-check fails as LinkedList does not implement RandomAccess.

Upvotes: 5

Related Questions