Issue created if Optional isEmpty() and following get()

First of all I’m using SonarLint plugin v4.0.2.3009 with IntelliJ Ultimate and I have this tiny snippet of code:

if (!exampleOpt.isPresent()) {
  // do something useful
  return;
}

Example example = exampleOpt.get();

SonarLint creates an issue for not simplifying the if-condition to “exampleOpt.isEmpty()”. If I change this, the call to Optional.get() afterwards creates an issue for calling get() without a preceeding call to isPresent(). So either way, if at runtime the get() call is reached, one can be sure the Optional is not Empty so it’s safe to call get(). How can I get SonarLint to recognize this and not creating false-positive issues out of this?

Hi, I believe that under the hood the version of sonarjava used is prior to 5.12.1 which contains this fix : https://jira.sonarsource.com/browse/SONARJAVA-3087

Your problem is a duplicate of this one : squid:S3655 (Optional use without isPresent) should not fire if .isEmpty() was called

So upgrading to latest SonarLint or updating sonarjava on your sonarqube instance should make the issue go away.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.