@Nullable input in Google Guava Function interface triggers FindBugs warning

Your implementation is wrong 😉

Basically docs says (I’ll paraphrase and emphasise):

@throws NullPointerException if input is null and the concrete
function implementation
does not accept null arguments

By implementing your function you must decide if it accepts nulls or not. In first case:

private static final class Example implements Function<MyBean, String> {
    @Override
    @Nullable
    public String apply(@Nullable MyBean input) {
        return input == null ? null : input.field;
    }
}

In second case:

private static final class Example implements Function<MyBean, String> {
    @Override
    @Nullable
    public String apply(MyBean input) {
        if (null == input) {
            throw new NullPointerException();
        }
        return input.field;
    }
}

In both examples returning null is allowed.

EDIT:

Note that Guava uses @javax.annotation.ParametersAreNonnullByDefault on all packages, hence if @Nullable is present it means “suspend global @Nonnull and allow nulls here” and if not it means “nulls forbidden here”.

That said, you may want use @Nonnull annotation on your argument or @ParametersAreNonnullByDefault in package to tell FindBugs Function’s argument can’t be null.

EDIT 2:

Turns out this case is known issue, see comment #3 (from Guava’s lead dev Kevin Bourrillion, about his conversation with Bill Pugh, Findbugs’ lead):

My reference was a series of in-person conversations with Bill Pugh.
He asserted unambiguously that @Nullable means only that some subtypes
might accept null. And this seems to be borne out by findbugs for us — our code passes the nullability checks pretty cleanly (though we
should check again since this particular Function change was made).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)