False positive for S1941 "Variables should not be declared before they are relevant"

  • Operating system: Linux
  • IDE name and flavor/env:
    Using sonarlint as Java library via gradle:
    {module = “org.sonarsource.sonarlint.core:sonarlint-core”, version = “” }
    { module = “org.sonarsource.java:sonar-java-plugin”, version = “” }

Getting a false positive for the following code:

package com;
public class MyExample {
	private static List<String> getEntities(String path, Entity entity) {
		List<String> entities = new ArrayList<>();
		TraversalUtils.traverseWithKey(rootEntities, (path, entity) -> {
			if (entity.getType() == EType.NAME) {
				return false;
			if (isFiltered(entity, path)
					&& !entity.getType().endsWith(TypeNames.NAME)) {
				int start = calculateStart(entity);
				int end = calculateEnd(entity);
				return false;
			return true;
		return entities;

Message is

Move the declaration of entities closer to the code that uses it

But that’s not possible. Seems like the lambda is not taken into account correctly.

Hello @naraesk ,

Thank you for the report.

First off, may I ask why you are using SonarLint as a Java library via Gradle? For Gradle, the recommended tool to use is the SonarScanner for Gradle.

Further, S1941 is not in the default quality profile. We don’t generally recommend enabling rules that are not in the default quality profile unless you have a very specific use case. Often, these rules’ result quality will be lower than of those enabled by default.

I was able to reproduce the issue, however, and agree that it is an FP. I created this ticket, which you can use to track the issue.