首页 > 解决方案 > 如何修复 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。我错过了什么?

标签: javajava-9

解决方案


有不同的解决方案,取决于是否getCode可以返回null

当您不希望预先评估替代表达式时,您必须使用orElseGet(Supplier<? extends T> other)而不是orElse(T other).

return Optional.ofNullable(clientTypeV2).map(ClientType::getCode)
    .orElseGet(() -> clientType.getCode());

如果getCode不能返回null,而你只想处理其中之一clientTypeV2clientType可能是的可能性null,你也可以使用

return Optional.ofNullable(clientTypeV2).orElse(clientType).getCode();

甚至更简单

return (clientTypeV2 != null? clientTypeV2: clientType).getCode()

所有解决方案的共同点是至少 on of clientTypeV2or clientTypeis not的假设null


推荐阅读