The concept of Optional is that it will be used when null could cause errors. In a way, it replaces null,
and when Optional is in use, there should never be a question of returning or receiving null from a call.
public void doSomething () {
Optional<String> optional = getOptional();
if (optional != null) { // Noncompliant
// do something with optional...
}
}
@Nullable // Noncompliant
public Optional<String> getOptional() {
// ...
return null; // Noncompliant
}
public void doSomething () {
Optional<String> optional = getOptional();
optional.ifPresent(
// do something with optional...
);
}
public Optional<String> getOptional() {
// ...
return Optional.empty();
}