null is passed to Optional.of or returned where an Optional is declared

tx0/java:null-where-empty-expecteddefaultwarningbug

What it finds

Optional stands for a value that may be missing, so that callers need not check for null. Optional.of(null) throws a NullPointerException, and a method declared to return an Optional that returns null makes its callers fail on the very check the type promised to spare them. Optional.empty() is the missing value.

From the rule's source, null_where_empty_expected.rs.

Example from the rule's tests
import java.util.Optional; class Lookup {  Optional<String> find(String key) {    if (key == null) {      return null;tx0 reports: this method returns null although it declares an Optional    }    java.util.function.Supplier<String> s = () -> {      return null;    };    return Optional.of(null);tx0 reports: Optional.of(null) throws  }   String plain() {    return null;  }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/java:null-where-empty-expected" = "off"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/java:null-where-empty-expected] reason="..."

tx0 explain tx0/java:null-where-empty-expected shows the same in the terminal. Found a false positive? Report it.