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?An intersection type combines multiple types into one. This allows you to add together existing types to get a single type that has all the features you need. For example, Person & Serializable & Loggable is a type which is all of Person and Serializable and Loggable .
In TypeScript, a union type variable is a variable which can store multiple type of values (i.e. number, string etc). A union type allows us to define a variable with multiple types. The union type variables are defined using the pipe ( '|' ) symbol between the types. The union types help in some special situations.
TypeScript allows you to define multiple types. The terminology for this is union types and it allows you to define a variable as a string, or a number, or an array, or an object, etc. We can create union types by using the pipe symbol ( | ) between each type.
The "property does not exist on type union" error occurs when we try to access a property that is not present on every object in the union type. To solve the error, use a type guard to ensure the property exists on the object before accessing it.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With