SonarLint analysis does not always detect Optional.filter() could make the Optional empty. (squid:S2589 )

SonarLint version 3.5.1.2759 for IntelliJ.

In the following example we have Java 8 Optionals, which could be empty due to the filter().
However, SonarLint highlights semicolon.isPresent() and comment.isPresent() as always being true. This is not the case, since line.indexOf() could return -1 which gets filtered out.

  private static Optional<Integer> findEnd(String line) {
    Optional<Integer> semicolon = Optional.of(line.indexOf(';')).filter(index -> index >= 0);
    Optional<Integer> comment = Optional.of(line.indexOf("//")).filter(index -> index >= 0);
    
    if (semicolon.isPresent() && comment.isPresent()) {
      return Optional.of(Math.min(semicolon.get(), comment.get()));
    } else if (comment.isPresent()) {
      return comment;
    } else {
      return semicolon;
    }
  }
1 Like

Indeed, that’s a false positive.
I created the following issue to track it:
https://jira.sonarsource.com/browse/SONARJAVA-2873.

Thanks a lot for the feedback!

Pierre-Yves

1 Like