2

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

Christoffer Hammarström
  • 27,242
  • 4
  • 49
  • 58
genxgeek
  • 13,109
  • 38
  • 135
  • 217

3 Answers3

5

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());
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
  • very cool! I like that approach! it would be nice if this was built into the library because it seems to me that having to check Optional variables for null defeats the entire purpose of the Optional Semantics. However, just goes to show you that a 3rd party method that says it will return Optional you can never trust it. – genxgeek Jun 10 '15 at 03:46
3

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

Ismail Badawi
  • 36,054
  • 7
  • 85
  • 97
0

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());
Christoffer Hammarström
  • 27,242
  • 4
  • 49
  • 58