I have the following java 11 code but eclipse is showing error 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){
}
Because basketRepository::findOneByKey
returns an Optional
, you can use Optional#flatMap
instead of Optional#map
so that you don't have to worry about nested Optional
s:
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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With