Kotlin false positive -- unused local variable in with block

We’re using Kotlin and the JetBrains exposed library and have some code that looks essentially like this:

val result = MyTable.select(blah).singleOrNull() ?: throw Exception()

with(MyTable) {
    val data = result[myTableColumn]
    // etc

where myTableColumn is a property on the MyTable object.

In the above code, SonarCloud reports the result variable as unused. I’m not sure if it’s because it’s only used inside of a with block, or because it’s only referenced as a map-like object, but it’s definitely used :slight_smile:

In fact…even much simpler cases still cause problems:

val removed = users.lookupRemoved()
return Response.newBuilder()

(simplified to protect company IP)

Looks like this is already being tracked here: [SONARKT-183] Kotlin compiler reports variables as unused with incomplete semantics - SonarSource

Hello Max, welcome to the community!

Thanks for the report! You worked out most of it already. Indeed, there is currently an issue with false positives when the compiler is missing some semantics. We will have a look into it in the context of the ticket you have already found. In the meantime, if these FPs are too noisy, you could work around the issue by either trying to fix the semantics for the analysis or disabling the rule until we ship a fix for it.

1 Like

I’ve disabled the rule for now. I suspect (or would hope, anyway) that either Detekt or ktlint would catch this, both of which we’re using; haven’t tested it yet.


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