java 不存在类型变量 U 的实例,因此 Optional<U> 符合 Response
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48784899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
No instance(s) of type variable(s) U exist so that Optional<U> conforms to Response
提问by user5325596
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
如果可能的话,我想避免调用isPresent
和get
调用,所以我尝试了
return update(resourceID, data).map(updatedResource -> Response.status(Response.Status.OK).entity(updatedResource).build();
but IntelliJ shows me the following error:
但是 IntelliJ 向我显示了以下错误:
No instance(s) of type variable(s) U exist so that Optional<U> conforms to Response
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
?
为什么我会收到这个错误,有没有办法避免它并避免isPresent
和get
?
采纳答案by Eran
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>
.
根据错误,您的方法的返回类型是Response
. 但是,update(resourceID, data).map(updatedResource -> Response.status(Response.Status.OK).entity(updatedResource).build())
返回Optional<U>
,因此您必须将返回类型更改为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:
或者,如果您不想更改返回类型,请添加orElse
调用以指定默认值:
public Response yourMethod (...) {
return update(resourceID, data).map(updatedResource -> Response.status(Response.Status.OK).entity(updatedResource).build()).orElse(defaultValue);
}