eclipse-jdt / eclipse-jdt/eclipse.jdt.core

Inferred type annotation remains @Nullable despite logic guaranteeing @NonNull

Open
#1,046 1 comment 0 reactions 0 assignees View on GitHub
null
Dominant language
Java
Stars
237
Forks
195
Avg merge
1d 12h
Merged PRs (30d)
47

Description

Below test code
```
public class Test {

public static final @NonNull Consumer CONSUMER = i -> { };

public static void main(String[] args) {
var a = method1();
CONSUMER.accept(a); // No message here
method3(CONSUMER, a); // No message here
var b = method2();
if(b != null) {
CONSUMER.accept(b); // No message here
method3(CONSUMER, b); // Type annotation message here
}
}

private static @NonNull Integer method1() {
return 1;
}

private static @Nullable Integer method2() {
return 2;
}

private static void method3(@NonNull Consumer consumer, @NonNull U argument) {
consumer.accept(argument);
}
}

```

produces the message `Null type safety (type annotations): The expression of type '@NonNull Consumer' needs unchecked conversion to conform to '@NonNull Consumer<@Nullable Integer>`.

Here is my attempt at understanding the cause of the problem:

- The variable `consumer` is first properly inferred as `@NonNull Integer`
- Later on, after checking for nullness, it is used as an argument of a method that is parameterized according to one of its arguments
- The original inferred type is used instead of the refined one, after the nullness check

Note that directly calling `CONSUMER(b)` works as intended.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.