如何修复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());
}

#Edit 1

我尝试过:

@JsonIgnore
public Integer getCodeClientTypeV2() {

return Optional.ofNullable(this.clientTypeV2)
.map(ClientType::getCode)
.orElse(this.clientType.getCode()) ;

}

在调试中,尽管填充了clientTypeV2,但是执行流程是进入orElse内部并给出NullPointerException,因为clientType为null。我想念什么?

解决方法

有不同的解决方案,具体取决于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()

所有解决方案的共同点是假设clientTypeV2clientType中的至少一个不是null

,

按照惯例,如果您使用的是orElse,则返回的是恒定的保证存在的orElse要么解开Optional中包含的值,要么使用您提供的默认值。

如果您不想更改方法签名,请改用Optional#or。您将必须对clientType对象的null检查保持聪明,因为如果该对象不存在,就不能依靠它作为具体的可返回事物。

return Optional.ofNullable(this.clientTypeV2)
               .map(ClientType::getCode)
               .or(this.clientType.getCode());