Keox
Keox

Reputation: 265

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 the Response interface, however, the compiler disagrees: "Type mismatch: cannot convert from TestResponse to T"

Upvotes: 2

Views: 132

Answers (1)

Jerome
Jerome

Reputation: 8447

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.

Upvotes: 4

Related Questions