I have an HTTP executor class:
Future<? extends Response> future = service.apply(request).toJavaFuture();
Now I want to remove the ? extends
part of this, because I don't want to make it so generic for the caller. Basically, I want to return Future<Response>
.
From my point of view:
x extends y
Would mean x
is y
, and y
is not x
.
That would mean x
can be casted to y
.
In my eyes, this can be done safely, because x
always extends y
.
Why is the following unsafe?
Future<? extends Response> future = service.apply(request).toJavaFuture();
Future<Response> futureResponse = (Future<Response>) future;
A Future<? extends Response>
variable can be assigned a Future<Response>
or a Future<ResponseSubClass1>
or a Future<ResponseSubClass2>
.
A Future<ResponseSubClass1>
instance cannot be safely assigned to a Future<Response>
variable, since that would allow assigning a ResponseSubClass2
to a Future<ResponseSubClass1>
.
Therefore, your attempted casting is unsafe.