如何在Java中使用Optional?

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

How to use Optional in Java?

问题

我有一个从数据库查询优惠券列表的服务。此服务向客户端返回一个Optional

return listOfCoupons.isEmpty() ? Optional.empty() : Optional.of(listOfCoupons.get(listOfCoupons.size() - 1));

而此代码的客户端以以下方式使用名为'coupons'的Optional

if (coupons.isPresent) {
   save(coupons.get());
} 

这个Optional的使用方式正确吗?

英文:

I have a Service which queries for a list of coupons from the database. This service returns an Optional to the client.

return listOfCoupons.isEmpty() ? Optional.empty() : Optional.of(listOfCoupons.get(listOfCoupons.size() - 1));

And the client of this code uses Optional named 'coupons' in the following way:

if (coupons.isPresent) {
   save (coupons.get());
} 

Is this the correct use of Optional ?

答案1

得分: 5

你使用的 Optional<T> API 从远处看起来很好,我看不到任何误用。如果我要挑剔并提出建议,我会将以下代码进行修改:

if (coupons.isPresent()) {
   save(coupons.get());
}

修改为:

coupons.ifPresent(c -> save(c)); // 或者使用方法引用

不过这实际上取决于个人口味。

英文:

Your use of the Optional&lt;T&gt; API looks fine from afar as I cannot see any misuse of it. if I were to nitpick and suggest something I would change:

if (coupons.isPresent) {
   save (coupons.get());
} 

to:

coupons.ifPresent(c -&gt; save(c)); //or method reference

but then again that's down to taste really.

huangapple
  • 本文由 发表于 2020年5月29日 04:30:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/62073990.html
匿名

发表评论

匿名网友

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

确定