类型不匹配:无法从Optional <object>转换为BasketDTO

时间:2019-04-11 23:01:40

标签: java optional

我有以下Java 11代码,但是eclipse显示错误Type mismatch: cannot convert from Optional<Object> to BasketDTO

    public BasketDTO findBasket(String key) {
        return Optional.ofNullable(key).map(basketRepository::findOneByKey)
                .map(b -> b.map(BasketDTO::new).orElseGet(() -> new BasketDTO()));
    }

    Optional<BasketModel> findOneByKey(String key){
    }

1 个答案:

答案 0 :(得分:2)

由于basketRepository::findOneByKey返回Optional,因此您可以使用Optional#flatMap代替Optional#map,这样就不必担心嵌套的Optional

public BasketDTO findBasket(String key) {
    return Optional.ofNullable(key) // Optional<String>
            .flatMap(basketRepository::findOneByKey) // Optional<BasketModel>
            .map(BasketDTO::new)        // b -> new BasketDTO(b)
            .orElseGet(BasketDTO::new); // () -> new BasketDTO()
}