Duplicate String Literals
ID |
kotlin.duplicate_string_literals |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Kotlin |
Tags |
maintainability, style |
Description
Reports string literals that appear the same value minOccurrences times or more inside a single class. Repeated literals should be extracted to a const val (or companion-object property) so a rename touches one place instead of many.
Rationale
Copies of the same literal are an open invitation to an inconsistency bug: one copy gets updated, the others don’t, and the mismatch lurks until a user hits it. Extracting to a constant also makes the string’s meaning explicit — MAX_RETRIES_EXCEEDED reads better than the raw "max_retries_exceeded" scattered across call sites.
The rule excludes literals inside annotation arguments (they are part of the configuration DSL, not executable code) and entire test classes — any class whose functions carry a JUnit / TestNG / kotlin.test annotation, since assertion fixtures legitimately repeat literals.
Remediation
Replace repeated literals with a const val or companion-object property.
// Before
class Reporter {
fun a() { log("error-message") }
fun b() { alert("error-message") }
fun c() { notify("error-message") }
}
// After
class Reporter {
companion object {
private const val ERROR_MESSAGE = "error-message"
}
fun a() { log(ERROR_MESSAGE) }
fun b() { alert(ERROR_MESSAGE) }
fun c() { notify(ERROR_MESSAGE) }
}