意外的返回值在使用 ifPresentOrElse lambda 函数时

huangapple go评论75阅读模式
英文:

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的值,并在没有值时执行其他逻辑。它不能用于返回值或抛出异常。

相反,您可以结合maporElseThrow来实现:

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);
}

huangapple
  • 本文由 发表于 2020年3月16日 19:00:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/60704717.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定