I have a list decorator that should, amongst a lot of other things, allow casting from one list to another. The idea is like that, and it already works:
public class ExtendedList<T> implements List<T> {
private List<T> delegate;
// constructors, methods, a collector, etc
public <R> ExtendedList<R> castTo(Class<R> targetType) {
return delegate.stream().map(item -> (R) item).collect(ExtendedList.toList());
}
}
I wonder if (and how) it is possible to restrict type parameter R
to valid casting targets like T
, all superclasses of T
and all interfaces that T
implements, so that the compiler can already check if casting is possible when I use it:
ExtendedList<Vehicle> vehicles = cars.castTo(Vehicle.class); // assuming Car implements Vehicle -> OK
ExtendedList<Dog> dogs = cars.castTo(Dog.class); // assuming Car does not extend Dog -> not OK