[Kotlin] False positive kotlin:S1144 (Unused "private" methods should be removed) on private operator fun get()/set()

SonarLint reports a false positive kotlin:S1144 (Unused “private” methods should be removed) for private operator fun get().

Given the following code


fun main() {
    KotlinS1144FalsePositive().callSet("foo", "bar")
    KotlinS1144FalsePositive().callGet("foo")
}

class KotlinS1144FalsePositive {
    private val map = mutableMapOf<String, String>()

    fun callGet(index: String): String? {
        return this[index]
    }

    fun callSet(index: String, value: String) {
        this[index] = value
    }

    @Suppress("kotlin:S1144")
    @SuppressWarnings("kotlin:S1144")
    private operator fun get(index: String) = map[index] // NOSONAR

    @Suppress("kotlin:S1144")
    @SuppressWarnings("kotlin:S1144")
    private operator fun set(index: String, value: String) { // NOSONAR
        map[index] = value
    }
}

Expected behavior when running SonarLint:
There’s nothing to report by check kotlin:S1144

Actual behavior when running SonarLint:
SonarLint reports private operator fun get(String) and private operator fun set(String, String) as unused.
SonarLint does not detect this[index] as a call to private operator fun get(String).
SonarLint does not detect this[index] = as a call to private operator fun set(String, String).

This issue could be observed via all ways that I attempted:

  • Gradle 6.4.1 via name.remal.sonarlint:gradle-plugins:1.0.192 which uses SonarLint version 4.11.0.18104
  • IntelliJ IDEA Ultimate Edition 2020.1.2 SonarLint Plugin 4.8.0.18115
  • SonarQube Community Edition Version 8.3.1 (build 34397), triggered via org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:3.0, using plugin SonarKotlin 1.5.0 (build 315)

Workarounds

  • Recommended workaround: Replace the private keyword with internal.
    This workaround might conflict with other static code analysis which may report the method(s) as “could be private” because of no uses outside the declaring class.
  • Suppress kotlin:S1144 in your build tool.
    This is not recommended, as this will suppress true positives as well.
    Example with Gradle:
sonarlint {
    excludes {
        message 'kotlin:S1144'
    }
}

P.S.:
All reasonable attempts to suppressing this false positive at the source are also not working (see the example, the suppressions are all ineffective).

Hi Christian,

Welcome to the community!

Thank you for your detailed report, I was able to reproduce your findings using your code example. I see two issues here. Firstly, the rule S1144 triggers for the operator functions, despite them being used with the square bracket syntax. I’ve created a ticket addressing this problem: https://jira.sonarsource.com/browse/SONARSLANG-490.

The second issue here seems to be the fact that you can’t stop the rule from triggering by suppressing it. I have also created a separate issue for that: https://jira.sonarsource.com/browse/SONARSLANG-491.