Search code examples
javajava-9

How to fix Java 9 Optional "Cannot return a void result" error message?


I had a class with a method like this:

public class Client {
    
private project.enums.ClientType clientType;

private ClientType clientTypeV2;


    @JsonIgnore
    public Optional<Integer> getCodeClientTypeV2() {
        
        return Optional.ofNullable(this.clientTypeV2).map(ClientType::getCode);
    }

}

But I would like to change the logic of this method. I want that if clientTypeV2 is filled, it returns the code for that object. Otherwise, I want it to return the code that is in the enum of the clientType. How to do this using java 8? I tried the following code but an error message appears "Cannot return a void result"

@JsonIgnore
public Optional<Integer> getCodeClientTypeV2() {

 return Optional.ofNullable(this.clientTypeV2).ifPresentOrElse(ClientType::getCode, () -> this.clientType.getCode());
}

#Edit 1

I tried this:

@JsonIgnore
public Integer getCodeClientTypeV2() {

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

}

In debug, although clientTypeV2 is filled, the execution flow is entering inside orElse and giving NullPointerException because the clientType is null. What am I missing?


Solution

  • There are different solutions, depending on whether getCode can return null.

    When you don’t want the alternative expression to be evaluated beforehand, you have to use orElseGet(Supplier<? extends T> other) instead of orElse(T other).

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

    If getCode can not return null and you only want to deal with the possibility that either clientTypeV2 or clientType can be null, you can also use

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

    or even simpler

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

    Common to all solution is the assumption that at least on of clientTypeV2 or clientType is not null.