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:
(List<Integer> & RandomAccess)linkedList
in an object of a specified type? takeList
method? 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, ie fulfills all interfaces. This runtime-check fails as LinkedList
does not implement RandomAccess
.
上一篇: 异步/等待模式和延续之间有什么关系?
下一篇: 相交类型的类型是什么?