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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With