且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Optional.ofNullable作为三元运算符的替代是一种好的做法吗?

更新时间:2022-06-13 23:10:27

每当我想到使用Optional API用于特定目的我总是提醒自己它打算做什么以及为什么它被带入JDK,即

Whenever I come to think of using the Optional API for a specific purpose I always remind my self of what it was intended to do and why it was brought into the JDK and i.e.


可选用于为库方法提供有限的机制
返回类型,其中明确需要表示无结果和
,其中使用null可能会导致错误 - Stuart Marks

Optional in intended to provide a limited mechanism for library method return types where there is a clear need to represent "no result" and where using null for this is overwhelmingly likely to cause errors - Stuart Marks

可选主要关注可能有也可能没有返回值的返回类型。

Optional is primarily focused on a return type that might or might not have a return value.

过度使用此结构就像在你的这个具体例子中一样,只会导致额外的内存分配和GC开销。

Over using this construct like in this specific example of yours just causes extra memory allocation and GC overhead.

我会保持简单而改为:

String hi = sayHi();
if(hi == null) hi = "-";
...