我有以下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){
}
答案 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()
}