我想更新如下条目:
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;
}
这段代码给了我以下错误消息:
Variable used in lambda expression should be final or effectively final
我该如何解决这个问题?
最佳答案
这里不要使用 lambda
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;
甚至更好
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);
关于java - 在 lambda 表达式中设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54307436/