java - 如何修复 Java 9 可选的“无法返回无效结果”错误消息?
问题描述
我有一个带有这样的方法的类:
public class Client {
private project.enums.ClientType clientType;
private ClientType clientTypeV2;
@JsonIgnore
public Optional<Integer> getCodeClientTypeV2() {
return Optional.ofNullable(this.clientTypeV2).map(ClientType::getCode);
}
}
但我想改变这种方法的逻辑。我希望如果clientTypeV2
已填充,则返回该code
对象的。code
否则,我希望它返回clientType
. 如何使用 java 8 做到这一点?我尝试了以下代码,但出现错误消息"Cannot return a void result"
@JsonIgnore
public Optional<Integer> getCodeClientTypeV2() {
return Optional.ofNullable(this.clientTypeV2).ifPresentOrElse(ClientType::getCode, () -> this.clientType.getCode());
}
#编辑 1
我试过这个:
@JsonIgnore
public Integer getCodeClientTypeV2() {
return Optional.ofNullable(this.clientTypeV2)
.map(ClientType::getCode)
.orElse(this.clientType.getCode()) ;
}
在debug中,虽然填了clientTypeV2,但是执行流程是进入orElse里面,因为clientType为null,所以报了NullPointerException。我错过了什么?
解决方案
有不同的解决方案,取决于是否getCode
可以返回null
。
当您不希望预先评估替代表达式时,您必须使用orElseGet(Supplier<? extends T> other)
而不是orElse(T other)
.
return Optional.ofNullable(clientTypeV2).map(ClientType::getCode)
.orElseGet(() -> clientType.getCode());
如果getCode
不能返回null
,而你只想处理其中之一clientTypeV2
或clientType
可能是的可能性null
,你也可以使用
return Optional.ofNullable(clientTypeV2).orElse(clientType).getCode();
甚至更简单
return (clientTypeV2 != null? clientTypeV2: clientType).getCode()
所有解决方案的共同点是至少 on of clientTypeV2
or clientType
is not的假设null
。
推荐阅读
- ios - FaceIDRecoginition 功能未实现,但要求在 info.plist 中添加 NSFaceIDUsageDescription 键
- cassandra - 如何在 cassandra 数据库中使用 like 运算符?
- perl - 在 Perl 中使用单个命令将元素添加到多个数组
- java - 检索 iASP RDB 名称以在 jdbc url 中指定它
- r - 如何在ggplot2中获得水平颜色渐变?
- c# - 使用 iText 以 pdf 形式展平字段后的矩形而不是字母
- ios - 从 json 提取时遇到问题
- android - Google 助理自定义命令 | 嘿 Google,打开我的应用页面
- c# - 版本控制 WebAPI C# - 通过模型类对 v1 和 v2 的不同响应
- sed - 将 NOPASSWD 字符串插入 sudoers 中不存在的正确位置