Java 使用ResponseEntity和Optional的不兼容类型

Java 使用ResponseEntity和Optional的不兼容类型,java,spring,Java,Spring,我尝试使用可选映射返回response ok,如果值存在,则返回值;如果不存在,则返回状态代码为4xx的映射 public ResponseEntity createUrl(@RequestBody String url){ return service.createUrl(url) .map(ResponseEntity::ok) .orElseGet(() -> ResponseEntity.status(

我尝试使用可选映射返回response ok,如果值存在,则返回值;如果不存在,则返回状态代码为4xx的映射

public ResponseEntity createUrl(@RequestBody String url){
        return service.createUrl(url)
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.status(HttpStatus.CONFLICT).body(Collections.singletonMap("error","Invalid url")));
}
上面说: 不兼容的类型。必需的ResponseEntity,但已将“body”推断为ResponseEntity:不存在类型变量K、V的实例,因此映射符合Url推断变量T具有不兼容的边界:相等约束:Url下限:映射

但它是这样工作的:

public ResponseEntity createUrl(@RequestBody String url){
        if(service.createUrl(url).isPresent()){
            return service.createUrl(url).map(ResponseEntity::ok).get();
        }else{
            return ResponseEntity.status(HttpStatus.CONFLICT).body(Collections.singletonMap("error","Invalid url"));
        }
}
来自服务的createUrl方法:

    public Optional<Url> createUrl(String url){
        try {
            URL myURL = new URL(url);
            URLConnection myURLConnection = myURL.openConnection();
            myURLConnection.connect();
            if(repository.existsByOriginalUrl(url)){
                return Optional.of(repository.getByOriginalUrl(url));
            }else{
                return Optional.of(repository.save(new Url(url,null)));
            }
        } catch (IOException e) {
            return Optional.empty();
        }
    }
public可选createUrl(字符串url){
试一试{
URL myURL=新URL(URL);
URLConnection myURLConnection=myURL.openConnection();
myURLConnection.connect();
if(repository.existsByOriginalUrl(url)){
返回可选的.of(repository.getByOriginalUrl(url));
}否则{
返回可选的.of(repository.save(新Url(Url,null));
}
}捕获(IOE异常){
返回可选的.empty();
}
}

我想避免使用isPresent()并用map()和orelsGet()解决这个问题。

究竟
createUrl
返回什么?它返回选项您可以显示方法声明和返回类型吗?检查我的答案,我想问的是,这个方法是由这个
ResponseEntity
代码组成的,而不是
createUrl
对不起,混淆了。使用optional,您不能返回两种不同类型的对象