Chaining Optional orElseThrow

  • A+
Category:Languages

I have a piece of code like this:

return getObject()     .map(obj -> obj.getNullableField())     .orElseThrow(() -> new IllegalStateException("Object not found!")); 

At the moment I'm throwing an exception when the given Object is not present.

Now I need to also check if the nullableField of Object is present. One obvious solution could be something like this:

var fieldVal = getObject()     .map(obj -> obj.getNullableField())     .orElseThrow(() -> new IllegalStateException("Object not found!"));    return Optional.ofNullable(fieldVal)      .orElseThrow(() -> new IllegalStateException("Field is not present")); 

But I'd like to implement this in the same functional chain...

What am I missing?

 


It could be implemented within the same chain directly, you would get different exception thrown. Now, it's less readable than your first solution of course, so you have a trade-off.

return getObject().map(obj -> Optional.ofNullable(obj.getNullableField())                                       .orElseThrow(() -> new IllegalStateException("Field is not present")))                   .orElseThrow(() -> new IllegalStateException("Object not found!")); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: