[Java] Sonar advises to remove a necessary cast thus leads to a compiling error

1. Versions used (SonarQube, Scanner, Plugin, and any relevant extension)

  • SonarLint 5.0.1.33703 for IntelliJ IDEA

  • Java Code Quality and Security 6.15.1.26025 shipped with the plugin

  • IntelliJ IDEA 2021.1.1 (Community Edition)

  • Build #IC-211.7142.45, built on April 30, 2021

  • Runtime version: 11.0.10+9-b1341.41 amd64

  • VM: Dynamic Code Evolution 64-Bit Server VM by JetBrains s.r.o.

2. Error observed (wrap logs/code around triple quote ``` for proper formatting)

  • Scanning log
Analysing 'App.java'...
Found 2 issues
  • Inspection description
SonarLint: Remove this unnecessary cast to "Callback".

3. Steps to reproduce

  • Save below piece of code as com/example/App.java

  • Sonar throw false positive java:S1905 at line #9 and line #10 where cast to Callback as screenshot #1 in below part

  • If you remove the cast as advised by Sonar, it cannot be compiled, as screenshot #2 in below part

package com.example;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.IntStream;

class App {
    Map<String, Callback> behaviors = mapOf(
            "onThisEvent", (Callback) this::takeThisAction,
            "onThatEvent", (Callback) this::takeThatAction
    );

    void takeThisAction() {
        // ...
    }

    void takeThatAction() {
        // ...
    }

    <K, V> Map<K, V> mapOf(Object... kvPairs) {
        return IntStream.range(0, kvPairs.length / 2).collect(HashMap::new, (map, i) -> map.put((K) kvPairs[i * 2], (V) kvPairs[i * 2 + 1]), HashMap::putAll);
    }
}

@FunctionalInterface
interface Callback {
    void call();
}

4. Screenshots

image

#bug:fp

Hello @NVXARM

First, thank you for taking the time to provide such a detailed description of the issue, it is really appreciated. It seems indeed like a false-positive.

Then, the good news is that we simplified greatly the implementation of this rule (see SONARJAVA-3794), and this issue is no longer reported.

The fix is available in version 7.0 of the Java analyzer.

Best,
Quentin

1 Like

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