英文:
Unexcepted return value when using ifPresentOrElse lamba function
问题
我似乎无法弄清楚为什么在使用lambda时,当我需要从一个方法返回值时,IDE显示Unexpected return value错误。
public Employee getEmployee(long id) {
repository.findById(id).ifPresentOrElse(
empDetails -> {
return service.buildEmployee(empDetails);
},
() -> { throw new ResourceNotFoundException(); }
);
}
谢谢!
英文:
I can't seem to figure out why I'm getting this error on the
IDE Unexpected return value when I need to return something from a method when using lambda.
public Employee getEmployee(long id) {
repository.findById(id).ifPresentOrElse(
empDetails -> {
return service.buildEmployee(empDetails);
},
() -> { throw new ResourceNotFoundException(); }
);
}
Thank you!
答案1
得分: 2
ifPresentOrElse用于在值存在时消耗Optional的值,并在没有值时执行其他逻辑。它不能用于返回值或抛出异常。
相反,您可以结合map和orElseThrow来实现:
public Employee getEmployee(long id) {
return repository.findById(id)
.map(service::buildEmployee)
.orElseThrow(ResourceNotFoundException::new);
}
英文:
ifPresentOrElse is used to consume the Optional's value if present, and to perform some other logic otherwise. It cannot be used to return a value or throw an exception.
Instead you can combine map with orElseThrow:
public Employee getEmployee(long id) {
return repository.findById(id)
.map(service::buildEmployee)
.orElseThrow(ResourceNotFoundException::new);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论