detekt icon indicating copy to clipboard operation
detekt copied to clipboard

UnusedPrivateClass Rule does not detect casts as usage

Open RaphaelTarita opened this issue 1 year ago • 0 comments

All described behavior below applies to the default detekt configuration (the one that is generated by the detektGenerateConfig gradle task)

Expected Behavior

UnusedPrivateClass should only trigger if a private class is not used in any way that is relevant to the code

Observed Behavior

If a private class is only used for a cast (using as), UnusedPrivateClass still triggers. If an explicit type annotation is used instead of the cast, UnusedPrivateClass does not trigger, even though the two cases are functionally the same.

Steps to Reproduce

The following code will trigger UnusedPrivateClass at 1:1:

private class Foo(val bar: String)

private val fooCasted = null as Foo?
// private val fooExplicitType: Foo? = null

fun use() {
    println(fooCasted)
    // println(fooExplicitType)
}

Commenting in fooExplicitType will remove the rule violation.

Context

The case with casting null to a nullable type is crafted to demonstrate the most simple reproduction example. For me, the issue arised because I declared a private external class in Kotlin/JS and tried to cast the result of a js("") call to this class:

private external class Crypto {
    val subtle: SubtleCrypto
}
private val crypto = js("window ? (window.crypto ? window.crypto : window.msCrypto) : self.crypto") as Crypto

When an explicit type is used instead of the cast:

private val crypto: Crypto = js("window ? (window.crypto ? window.crypto : window.msCrypto) : self.crypto")

the detekt rule violation goes away but the IDE warns me "Implicit (unsafe) cast from dynamic to Crypto" and suggests adding an explicit cast (which then removes the need to explicitly annotate the type of crypto).

Your Environment

  • Version of detekt used: 1.23.5
  • Version of Kotlin used: Kotlin/JVM 1.9.22
  • Version of Gradle used: 8.6
  • Gradle scan link: https://scans.gradle.com/s/xewkclerzfekg
  • Operating System and version: Windows 11

RaphaelTarita avatar Feb 19 '24 14:02 RaphaelTarita