Skip to content

Commit

Permalink
UnusedPrivateProperty: Fix false postive by ignoring data classes (de…
Browse files Browse the repository at this point in the history
  • Loading branch information
atulgpt authored and cortinico committed Jul 15, 2023
1 parent dee1ee8 commit 4d21309
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import io.gitlab.arturbosch.detekt.api.internal.Configuration
import io.gitlab.arturbosch.detekt.rules.isActual
import io.gitlab.arturbosch.detekt.rules.isExpect
import org.jetbrains.kotlin.com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtImportDirective
import org.jetbrains.kotlin.psi.KtNamedDeclaration
Expand Down Expand Up @@ -108,11 +109,17 @@ private class UnusedPrivatePropertyVisitor(private val allowedNames: Regex) : De
constructor.valueParameters
.filter {
(it.isPrivate() || (!it.hasValOrVar() && !constructor.isActual())) &&
it.containingClassOrObject?.isExpect() == false
it.containingClassOrObject?.isExpect() == false &&
isConstructorForDataOrValueClass(constructor).not()
}
.forEach { maybeAddUnusedProperty(it) }
}

private fun isConstructorForDataOrValueClass(constructor: PsiElement): Boolean {
val parent = constructor.parent as? KtClass ?: return false
return parent.isData() || parent.isValue() || parent.isInline()
}

override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor) {
super.visitSecondaryConstructor(constructor)
constructor.valueParameters.forEach { maybeAddUnusedProperty(it) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -747,6 +747,37 @@ class UnusedPrivatePropertySpec(val env: KotlinCoreEnvironment) {
""".trimIndent()
assertThat(subject.lint(code)).isEmpty()
}

@Test
fun `does not report unused private property in data class - #6142`() {
val code = """
data class Foo(
private val foo: Int,
private val bar: String,
)
""".trimIndent()
assertThat(subject.lint(code)).isEmpty()
}

@Test
fun `does not report unused private property in data class with named constructor`() {
val code = """
data class Foo constructor(
private val foo: Int,
private val bar: String,
)
""".trimIndent()
assertThat(subject.lint(code)).isEmpty()
}

@Test
fun `does not report unused private property in value or inline class`() {
val code = """
@JvmInline value class Foo(private val value: String)
inline class Bar(private val value: String)
""".trimIndent()
assertThat(subject.lint(code)).isEmpty()
}
}

@Nested
Expand Down

0 comments on commit 4d21309

Please sign in to comment.