Why is IntelliJ's inspector highlighting this code?

162 views Asked by At

IntelliJ seems to think that there is a potential bug with my code, and I can't quite see why. This has to do with the Nonnull annotations; I am telling IntelliJ that some fields cannot be null, and I am ensuring that they never are allowed to become null, but IntelliJ doesn't like it, all the same.

Here is an example of the code in question.

import javax.annotation.Nonnull;

public class Something {
     static final Long DEFAULT_ID = -1L;

     @Nonnull
     public Long id;

     public Something() {
         id = DEFAULT_ID;
     }

     @Nonnull
     public Long getId() {
         return this.id;
     }

     public Something setId(Long id) {
         this.id = id != null ? id : DEFAULT_ID;
         return this;
     }
}

When I do this, IntelliJ's inspector produces a warning on the id parameter of the setId(Long) method prototype, warning me that the class field for id is annotated with Nonnull. This is in spite of me manually checking for null in the body of the method & handling it if need be. Something#id will never become null via this method.

However, if I change the method to be like this, the inspection warning goes away entirely:

public Something setId(Long id) {
    if (id != null) 
        this.id = id;
    else 
        this.id = DEFAULT_ID; 
    return this;
}

In theory, both implementations are effectively the same; in fact, IntelliJ recommends using the ternary operator when I go with the if-else approach, for stylistic purposes. Why would IntelliJ produce a warning on the first implementation--using the ternary operator--but not the second? Is this just an oversight in the code inspector, or am I missing something important here? The warning can be suppressed by suppressing "NullableProblems", but I want to make sure that there isn't something wrong with using the ternary operator here. Any advice?

1

There are 1 answers

0
eekboom On BEST ANSWER

This looks like a bug.

I create an issue in JetBrains tracker for you.

Vote/comment here: https://youtrack.jetbrains.com/issue/IDEA-178172