java:S1612 not equivalent class::cast method reference on generic class

SonarLint for IntelliJIdea 5.3.0.36775 connected to SonarCloud,
SDK java16
Source target java11

SonarLint fires S1612 on casting to class with generic type.

  @SuppressWarnings("unchecked")
  public Map<String, CodeLensSupplier<CodeLensData>> codeLensSuppliersById(
    Collection<CodeLensSupplier<? extends CodeLensData>> codeLensSuppliers
  ) {
    return codeLensSuppliers.stream()
      .map(codeLensSupplier -> (CodeLensSupplier<CodeLensData>) codeLensSupplier)
      .collect(Collectors.toMap(CodeLensSupplier::getId, Function.identity()));
  }

Sonarlint wants to replace (CodeLensSupplier<CodeLensData>) codeLensSupplier) with CodeLensSupplier.class::cast which procudes CodeLensSupplier raw class and next collector fails compile with error:

error: incompatible types: cannot infer type-variable(s) T#1,K,U,T#2
      .collect(Collectors.toMap(CodeLensSupplier::getId, Function.identity()));
              ^
    (argument mismatch; Function<CodeLensSupplier,CodeLensSupplier> cannot be converted to Function<? super CodeLensSupplier,? extends CodeLensSupplier<CodeLensData>>)
  where T#1,K,U,T#2 are type-variables:
    T#1 extends Object declared in method <T#1,K,U>toMap(Function<? super T#1,? extends K>,Function<? super T#1,? extends U>)
    K extends Object declared in method <T#1,K,U>toMap(Function<? super T#1,? extends K>,Function<? super T#1,? extends U>)
    U extends Object declared in method <T#1,K,U>toMap(Function<? super T#1,? extends K>,Function<? super T#1,? extends U>)
    T#2 extends Object declared in method <T#2>identity()

Hello @nixel2007

I agree that this rule should not suggest using method references for generic classes.
Ticket created: SONARJAVA-4040.

Thanks for reporting this issue.
Best,
Quentin

1 Like

Hello, @Quentin.
Thanks for the link.

Looks like there is small typo in method signature in your example.
It should take List<MyClass<Object>> instead of List<Object>

1 Like

Not sure to understand, if I change the code as suggested, I have an error: Inconvertible types;.

In any way, the exact code sample is not that important, as long as we get the idea.

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