您好,我有一个返回
Mono<ResponseEntity<Void>>
的 API,该 API 将调用另一个返回 Mono<ResponseEntity<Object>>
的 API,如何将其他 API 的结果转换为 Mono<ResponseEntity<Void>>
?例如
public Mono<ResponseEntity<Void>> api() {
return anotherApi()
.map(response -> ResponseEntity.ok().build())
.onErrorReturn(ResponseEntity.badRequest().build());
}
如果我只有
map
,上面的工作,但当我添加onErrorReturn
时,它会抱怨Type mismatch: cannot convert from Mono<ResponseEntity<Object>> to Mono<ResponseEntity<Void>>
,为什么它变成了Mono<ResponseEntity<Object>>
?
代码是正确的,这只是无法正确推断类型的 Java 泛型。
您可以明确提供类型
public Mono<ResponseEntity<Void>> api() {
return anotherApi()
.<ResponseEntity<Void>>map(response -> ResponseEntity.ok().build())
.onErrorReturn(ResponseEntity.badRequest().build());
}
或移动
onErrorReturn
一层
public Mono<ResponseEntity<Void>> api() {
return anotherApi()
.onErrorReturn(ResponseEntity.badRequest().build())
.map(response -> ResponseEntity.ok().build());
}