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 toCallback
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();
}