Found shadowed variable declarationKT-W1045
Name shadowing in software development is considered bad practice in programming. Firstly, it hampers readability and understandability of the code, as it introduces ambiguity and confusion. When a variable or identifier is shadowed, it becomes unclear which one is being referenced, especially in nested scopes or complex code.
Secondly, name shadowing can lead to maintenance and debugging difficulties. Unintentional or undocumented shadowing can cause unexpected behavior or incorrect results. Identifying and fixing such issues becomes challenging, as the code may appear correct but is affected by hidden shadowed variables.
To write clean and maintainable code, it is advisable to avoid name shadowing. Choosing distinct and descriptive names for variables and identifiers, along with proper scoping, enhances code readability, reduces bugs, and facilitates easier maintenance and debugging.
Bad Practice
// Parameters to the function `test` are named `i`, `j`, and `k`.
// But these names are used again in the body of the function for other variables.
fun test(i: Int, j: Int, k: Int) {
val i = 1
val (j, _) = 1 to 2
listOf(1).map { k -> println(k) }
listOf(1).forEach {
listOf(2).forEach {
}
}
}
Recommended
Rename variables that shadow other variables.
fun test(i: Int, j: Int, k: Int) {
val x = 1
val (y, _) = 1 to 2
listOf(1).map { z -> println(z) }
listOf(1).forEach {
listOf(2).forEach { x ->
}
}
}