java:S6212 erroneously reporting when a method has parameterized return types

Given a method with a parameterized return type, e.g.:
public <T> T getValue() { ... }

Sonar reports S6212, “use ‘var’” for the following:
MyType result = getValue();

Unfortunately, if “MyType” is replaced with “var”, then the java compiler doesn’t know the type of “result” and just assumes that it’s a plain Object, which is not typically correct.

  • Potential workaround
    It’s messier, but the following can be used instead:
    var result = (MyType) result;

Hello @jrh3

I agree that the rule should not raise an issue in this case and that the workaround is not something I would recommend using.

Ticket created: SONARJAVA-3839.


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