How to wrap a method that returns an optional <T> with fromNullable?

1.1k views Asked by At

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;
}

enter image description here

3

There are 3 answers

1
Tagir Valeev On BEST ANSWER

Use

Optional<Boolean> x = get_I_dontHaveControlOverThisMethod();
if(x == null) x = Optional.absent();

If you are calling such methods quite often, you can wrap it into function:

static <T> Optional<T> safeOptional(Optional<T> optional) {
    return optional == null ? Optional.absent() : optional;
}

And use:

Optional<Boolean> x = safeOptional(get_I_dontHaveControlOverThisMethod());
0
Ismail Badawi On

The type of Optional.fromNullable(get_I_dontHaveControlOverThisMethod()) would be Optional<Optional<Boolean>>, not Optional<Boolean>.

0
Christoffer Hammarström On

You can "unwrap" or "flatten" the Optional<Optional<Boolean>> with .or(Optional.<Boolean>absent()):

Optional<Boolean> x = Optional.fromNullable(get_I_dontHaveControlOverThisMethod())
            .or(Optional.<Boolean>absent());