Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

"unspecified" local variables complain but need to be annotatable with "@Nullable" or to be excluded from the Marking-Requirements

27 views
Skip to first unread message

PBoe

unread,
May 29, 2024, 12:36:14 PM5/29/24
to jspecify-discuss
Let's say, I implement a "Poller<E>" class, delegating the "poll()" method to a Queue<E>.

The Javadoc of "poll()" says: return "null", if Collection is empty. Otherwise return the element of e.g. Type E.

Now the Poller does something, if the element wasn't "null" and otherwise it does something. So the Result of "delegate.poll()" is stored in a local variable which for this reason can be "null", and hence would need the annotation "@Nullable".

I get "yellow" Code (i highlighted it in the snippets below in RED) either on the "delegate.poll()" or on the "@Nullable" added to the local variable:

Here is the example code causing unexpected problems, due to the use of "@NullMarked":

import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;

import java.util.concurrent.ConcurrentLinkedQueue;

@NullMarked
public class Test<E> {
  private final ConcurrentLinkedQueue<E> delegate = new ConcurrentLinkedQueue<>();

  public @Nullable E poll1() {
    final @Nullable E poll = delegate.poll();
    if (poll != null) {
      // do something, since an element was removed
    }
    return poll;
  }

  public @Nullable E poll2() {
    final E poll = delegate.poll();
    if (poll != null) {
      // do something, since an element was removed
    }
    return poll;
  }
}


Seems like the "var" case somehow like mentioned in:
Issue 301

I hope it will be considered to allow the "@Nullable" annotation on local variables for this case.

Chris Povirk

unread,
Jul 16, 2024, 10:48:18 AM7/16/24
to PBoe, jspecify-discuss
Is this a problem that you are seeing in IntelliJ? If so, there's a bug that was filed against IntelliJ for it: IDEA-348069.
Reply all
Reply to author
Forward
0 new messages