'Unused local variables should be removed' rule is BROKEN

The rule is broken and marks as code smell, variable definitions that are clearly used a couple lines below. Sample code that shows issues:

val usedVariable = someRandomFunction() ?: throw someException.badRequest("Message")
anotherClass.validPublicMethod(usedVariable, something.weDontCareAbout())

The usedVariable in this case is shown as unused

1 Like

Hello George,

Thanks for your report. I was not able to reproduce the false positive based on the code you provided. Do you have a complete reproducer available or is the project in which you have observed this behavior public?

Hey Johann,

This is a private project, so I’d be happy to send it to you privately if you open up a conversation.

Best,
George

Hello George,

This particular rule uses the Kotlin compiler diagnostics directly and doesn’t actually perform an additional analysis itself. It looks like the compiler may not be able to resolve everything correctly. Could you please check which values you have set for sonar.java.binaries and sonar.java.libraries and if these values point to the correct locations?

I’m seeing something similar in SonarLint in Android Studio, but not in the analysis from SonarQube. The code getting flagged by SonarLint is:

fun someMethodThatRequiresActivity() {
    val activity = activity ?: return
    ...
    activity.doSomethingWithIt()
}

… where “activity” is an optional (nullable) member variable on the class

Sorry about the delay. We’ve setup those parameters as mentioned by Alexandre here to save on time. Kolin project scan times dramatically increased today! Why? - #9 by geojakes

We strongly recommend against not configuring these parameters properly, as Alexandre has already indicated in the other thread. The quality of the results will most certainly degrade.

If you really want to go down this road (again: we heavily recommend against this!), you can check if you have set the parameters to a dot (.) and you can try setting them to an empty string instead. This may get rid of some false positives, no guarantees though. If libraries and binaries are unknown to the analysis, you cannot expect the results as good as if they were known.

That makes sense. Though I’m curious, isn’t this more a syntactic issue than semantic to be resolved by libraries?

I agree with you that there is definitely room for improvement here and that some situations could be detected with higher precision, even if semantics are unavailable. I’ve created a ticket to track these FPs. Please be aware that tackling this issue is currently not the highest priority, so I cannot give you an exact ETA for a potential fix.

1 Like

Quick update: the issue has been fixed at the end of 2021 and is deployed on SonarCloud. If you find any other false positives please report them in a new thread, I am going to close this one.

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