Java 8 之 Optional 的使用场景
2023/10/12
相关信息
Brian Goetz (Java语言设计架构师)对 Optional 设计意图的解释:
Optional is intended to provide a limited mechanism for library method return types where there needed to be a clear way to represent “no result," and using null for such was overwhelmingly likely to cause errors.
从中可以看出,Optional 主要目的是用于处理返回值可能为空的情况。
1. Optional 使用注意事项
(1). 不要把容器类型(如 List, Map 等)等包装在 Optional 中。
因为容器类都有自己空值设计,如 Collections.emptyList()
(2). 不要使用 Optional 作为方法参数的类型
当参数类型为 Optional 时,所有 API 调用者都需要给参数先包一层 Optional(额外创建一个Optional实例),浪费性能。
(3). Optional 无法序列化。
Using Optional in a serializable class will result in a NotSerializableException.
2. Optional 的应用场景
(1). 重复的 if 逻辑,并重复的 null 判断的时候
例:
String version = "UNKNOWN";
if(computer != null){
Soundcard soundcard = computer.getSoundcard();
if(soundcard != null){
USB usb = soundcard.getUSB();
if(usb != null){
version = usb.getVersion();
}
}
}可以优化为:
String version = Optional.ofNullable(computer)
.map(Computer::getSoundcard)
.map(Soundcard::getUSB)
.map(USB::getVersion)
.orElse("UNKNOWN");(2). 返回值,易于后期拆解处理
如:
User user = users.stream().findFirst().orElse(new User("default", "1234"));