I have a method that I don't own that is returning null but return type is Optional<Boolean>. When I call x.IsPresent() it throws (scenario #2). I tried wrapping the method in a fromNullable but I get a type mismatch (screen shot below). How can I fix so IsPresent() doesn't throw?
import com.google.common.base.Optional;
private Optional<Boolean> get_I_dontHaveControlOverThisMethod () {
return null; // Ooops!
}
// Compile error? -----------------------> vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Optional<Boolean> x = Optional.fromNullable(get_I_dontHaveControlOverThisMethod());
// (#1) Optional<Boolean> x = Optional.fromNullable(null); // <- this work fine
// (#2) Optional<Boolean> x = get_I_dontHaveControlOverThisMethod();
if (x.isPresent()) { // <- this blows up! NPE when (#2) runs
// non-null good value;
}
Use
If you are calling such methods quite often, you can wrap it into function:
And use: