tags:

views:

60

answers:

1

Hello,

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"

+4  A: 

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.

Jerome
Yes, thank you. Now I understand the compiler's concern.
Keox
Pleased to help you. If this answer was helpful, please accept it by clicking on the green check on the left. Thank you!
Jerome