0

I want to update an entry as following:

public Entry updateEmail(String nom, EntryRequest entryReq) {
        Optional<Entry>  optional =  entryRepository.findByNom(nom);
        Entry updatedEntry = null;
        optional.ifPresent(entry -> {
            if(!StringUtils.isEmpty(entryReq.getEmail())){
                entry.setEmail(entryReq.getEmail());
            }
            updatedEntry = save(entry);
        });
        optional.orElseThrow(() -> new NotFoundException(this.getClass().getName()));
        return updatedEntry;
    }

This code gives me the following error message :

Variable used in lambda expression should be final or effectively final

How can I solve this ?

0

2 Answers 2

3

Just don't use lambda here

Optional<Entry>  optional =  entryRepository.findByNom(nom);
Entry updatedEntry = null;
if(optional.isPresent()){
    Entry entry=optional.get();
    if(!StringUtils.isEmpty(entryReq.getEmail())){
        entry.setEmail(entryReq.getEmail());
    }
    updatedEntry = save(entry);
});
optional.orElseThrow(() -> new NotFoundException(this.getClass().getName()));
return updatedEntry;

or even better

Optional<Entry>  optional =  entryRepository.findByNom(nom);
Entry entry=optional.orElseThrow(() -> new NotFoundException(this.getClass().getName()));
    if(!StringUtils.isEmpty(entryReq.getEmail())){
        entry.setEmail(entryReq.getEmail());
    } 
return save(entry);
Sign up to request clarification or add additional context in comments.

Comments

1

You can actually use the map method of Optional to process the save in case the initial entry exists:

public Entry updateEmail(String nom, EntryRequest entryReq) {
    Optional<Entry>  optional =  entryRepository.findByNom(nom);
    Entry updatedEntry = optional.map(entry -> {
        if(!StringUtils.isEmpty(entryReq.getEmail())){
            entry.setEmail(entryReq.getEmail());
        }
        return save(entry);
    }).orElseThrow(() -> new NotFoundException(this.getClass().getName()));
    return updatedEntry;
}

A bit more concisely:

public Entry updateEmail(String nom, EntryRequest entryReq) {
    Optional<Entry>  optional =  entryRepository.findByNom(nom);
    return optional.map(entry -> {
        if(!StringUtils.isEmpty(entryReq.getEmail())){
            entry.setEmail(entryReq.getEmail());
        }
        return save(entry);
    }).orElseThrow(() -> new NotFoundException(this.getClass().getName()));
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.