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 ?

Yogendra Mishra
  • 2,399
  • 2
  • 13
  • 20
Renaud is Not Bill Gates
  • 1,684
  • 34
  • 105
  • 191

2 Answers2

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);
Antoniossss
  • 31,590
  • 6
  • 57
  • 99
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()));
}
gil.fernandes
  • 12,978
  • 5
  • 63
  • 76