Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type mismatch: cannot convert from Optional<Object> to BasketDTO

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){
    }
like image 651
Saurabh Kumar Avatar asked Apr 11 '19 23:04

Saurabh Kumar


1 Answers

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 Optionals:

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()
}
like image 108
Jacob G. Avatar answered Nov 18 '22 17:11

Jacob G.