java:S6204 Suggestion of using .toList() in a List that is from the interface does not compile

SonarCloud is constantly asked to use .toList() in addition to .collect(Collectors.toList()) but in some cases this request is wrong as the solution simply won’t compile.

Here’s a small example:

@RequiredArgsConstructor
public class ReturnTestSonar {
    @Getter private final List<TestSonar> list;
    
    @RequiredArgsConstructor
    public static class TestSonarImpl implements TestSonar {
        @Getter private final Integer integer;
    }

}


public class SonarViolation {
        
    public List<TestSonar> teste(List<Integer> list) {
        return list.stream().map(TestSonarImpl::new).collect(Collectors.toList());
    }
    
    public ReturnTestSonar myList(List<Integer> list) {
        return new ReturnTestSonar(list.stream().map(TestSonarImpl::new).collect(Collectors.toList())); 
    }
}

The solution not compile, because then I would have to change the return of the method to be the TestSonarImpl instead of the interface TestSonar.

Hi @Irineu_Ruiz,

I tried reproducing this issue, but without success.
Can you please check if you added an intended code example?
Also, does the rule raise in SonarLint?
Thanks!

All the best,

Irina

Hi @irina.batinic ,

We use Sonarlint and Sonar cloud with the default settings.
Apparently the problem has already been resolved, I tested it today and now it is no longer giving the java:S6204 violation.
Even our production code that reported this has now stopped reporting in Sonar Cloud.

Thank you very much, it’s resolved.

1 Like

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