Optionally getting field
Why you dont add a getValue
methode to the class Foo
? This would be a kind of delegation.
public class Foo {
...
public Integer getValue() {
if (foob == null) {
return null;
}
return foob.getValA();
}
}
What you are describing is the method Optional.map
:
Integer valA = foo.getFoob().map(foo -> foo.getValA()).orElse(null);
map
lets you transform the value inside an Optional
with a function if the value is present, and returns an empty the optional if the value in not present.
Note also that you can return null from the mapping function, in which case the result will be Optional.empty()
.