FP java:S2637 for NonNull return type used in Optional.map(...).orElse(null)

False positive when method return value is marked with Lombok NonNull and it is used in Optional.map(…).orElse(null). It should not be raised because no value marked as @NonNull is assigned here, only read, and also the value is never null.

Rule affected: java:S2637 ["@NonNull" values should not be set to null]
SonarQube version 9.2.2 (build 50622)
SonarLint plugin 6.3.1.40498 in IntelliJ 2021.1.3
Java 17

Example:

import java.util.Optional;
import lombok.NonNull;

public class A {
    private final String value = "value";

    @NonNull // when this is removed the error disappears
    public String getValue() {
        return value;
    }


    public static void main(String[] args) {
        Optional<A> a = Optional.empty();
        System.out.println(
            a.map(A::getValue)
                .orElse(null)   // here is an error
        );
    }
}

Hi @blazar,

Thank you for your report and the reproducer. Indeed, this is a false positive. There seems to be a bug that causes SonarQube to think that orElse's parameter is marked @NonNull when it’s not. I’ve created a ticket for this bug.

Cheers,
Sebastian

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.