Skip to content

False positive for using nullable method with strict Contract("null -> null; !null -> !null") as a function !null -> !null #1502

@unv-unv

Description

@unv-unv

We have a method (toUpperCase) which returns null only if its argument is null. Otherwise it always returns not null. So it ensures non-null result for non-null argument and can be safely passed as lambda to be used in non-null context. But NullAway doesn't detect this situation and shows error:

@NullMarked
public class Test {
    @Contract("null -> null; !null -> !null")
    public @Nullable String toUpperCase(@Nullable String s) {
        return s == null ? null : s.toUpperCase(Locale.US);
    }

    public String[] map(String[] strings, Function<String, String> mapper) {
        String[] result = new String[strings.length];
        for (int i = 0, n = strings.length; i < n; i++) {
            result[i] = mapper.apply(strings[i]);
        }
        return result;
    }

    public String[] capitalizeWords(String[] words) {
        // BUG: [NullAway] referenced method returns @Nullable, but functional interface method java.util.function.Function.apply(T) returns @NonNull
        return map(words, StringUtil::toUpperCase);
    }
}

NullAway 0.13.1, Error Prone 2.48.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions