-1

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!

mengmeng
  • 1,266
  • 2
  • 22
  • 46

1 Answers1

2

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);
}
Eran
  • 387,369
  • 54
  • 702
  • 768