A problem with parametrized return value type
I am somewhat new to the Java Generics feature. Can you please help me to figure out why the code snippet below does not work:
interface Response {}
interface Request<T extends Response> {}
class TestResponse implements Response {}
class TestRequest implements Request<TestResponse> {}
<T extends Response> T foo(Request<T> b) {
TestResponse tr = new TestResponse();
return tr;
}
Everything seems good to me: the return value type implements开发者_如何学Python the Response interface, however, the compiler disagrees: "Type mismatch: cannot convert from TestResponse to T"
Let's imagine the following use of your API:
OtherRequest<OtherResponse> req = new OtherRequest<OtherResponse>();
OtherResponse res = foo(req);
You see the problem? Your implementation returns a TestResponse, which is not a subclass of OtherResponse.
精彩评论