Guava Optional and @NonNull annotation

2.2k views Asked by At

I'm trying different ways of getting rid of NPEs in my code. I use nullness analysis in Eclipse and I'm quite fond of @NonNullByDefault. But today I run into a problem with guava's Optional:

private static Optional<Foo> bar() {
  Foo foobar = new Foo();
  return Optional.of(foobar);
}

I get following comment on the return line:

Null type safety: The expression of type 'Optional<Foo>' needs unchecked conversion to conform to   '@NonNull Optional<Foo>'

I tried using JSR305 annotations to no avail. Is there a way to make it work (use both Optional and @NonNull annotations)?

2

There are 2 answers

0
Stephan Herrmann On

The full solution to this question requires null annotations in the Optional API. In particular of() should be declared to return @NonNull.

Until the library authors annotate their API, you will need external annotations, support for which is being developed for Eclipse Mars. See https://wiki.eclipse.org/JDT_Core/Null_Analysis/External_Annotations

OTOH, I'm curious, why indeed you want both concepts for NPE avoidance combined in one project.

0
dimo414 On

Guava code treats non-null as the default, but it doesn't use Eclipse's @NonNullByDefault annotation, since it's non-standard. Instead it uses the standard @Nullable annotation to indicate parameters and return types that can be null.

The awesome Error Prone project provides null-safety checks that are compatible with this standard approach - I'd suggest using it rather than your IDE's custom checks.