Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't use parent as variable types and yet receive child types

Tags:

java

retrofit2

Hi I am working with java 8. Below is the case:

I have an empty interface AsyncResponse like below:

package com.personal.carrot.core.models;

public interface AsyncResponse {
}

And I have a model APIResponse

package com.personal.carrot.core.models;

import org.codehaus.jackson.annotate.JsonProperty;

public class APIResponse implements AsyncResponse {

    @JsonProperty("numberOfFeatures")
    public Long numberOfFeatures;

}

And finally I have a service using Retrofit2 to make my API response:

public interface APIRepository {
    @POST("MYURL")
    Call<APIResponse> resolveCounts(@Body HashMap<String, String> body);
}

Now when I call the APIRepository like below:

Call<AsyncResponse> request = repository.resolveCounts(payload);

I get an error:

java: incompatible types: retrofit2.Call (com.personal.carrot.core.models.APIResponse) cannot be converted to retrofit2.Call(com.personal.carrot.core.models.AsyncResponse)

like image 631
iam.Carrot Avatar asked Nov 07 '22 21:11

iam.Carrot


1 Answers

It's failing because you cannot assign a Call<APIResponse> to a Call<AsyncResponse>. Generic types are invariant.

You probably have to use APIResponse as type argument for your variable:

Call<APIResponse> request = repository.resolveCounts(payload);

That is not because you can't design your code to use the interface AsyncResponse, but because (I'm presuming here) the framework uses the return type to process content-type-related bindings.

like image 164
ernest_k Avatar answered Nov 13 '22 01:11

ernest_k