简体   繁体   中英

No instance(s) of type variable(s) U exist so that Optional<U> conforms to Response

I have the following:

Optional<Resource> updatedResource = update(resourceID, data);

if (updatedResource.isPresent()) {
    return Response.status(Response.Status.OK).entity(updatedResource.get()).build();
}

I would like to avoid the isPresent and get calls if possible, so I tried

return update(resourceID, data).map(updatedResource -> Response.status(Response.Status.OK).entity(updatedResource).build();

but IntelliJ shows me the following error:

No instance(s) of type variable(s) U exist so that Optional<U> conforms to Response

Why do I get this error, and is there a way to avoid it and also avoid isPresent and get ?

Based on the error, the return type of your method is Response . However, update(resourceID, data).map(updatedResource -> Response.status(Response.Status.OK).entity(updatedResource).build()) returns an Optional<U> , so you have to change the return type to Optional<Response> .

So the method would look like this:

public Optional<Response> yourMethod (...) {
    return update(resourceID, data).map(updatedResource -> Response.status(Response.Status.OK).entity(updatedResource).build());
}

Or, if you don't want to change the return type, add an orElse call, to specify a default value:

public Response yourMethod (...) {
    return update(resourceID, data).map(updatedResource -> Response.status(Response.Status.OK).entity(updatedResource).build()).orElse(defaultValue);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM