Safely casting <? extends Response> to <Response>

Randy :

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;

Eran :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324332&siteId=1