I’m on the exactly opposite camp. I’d rather have name shadowing removed completely from Kotlin. I’m not sure about shadowing a field with a local variable, but shadowing a local variable with another local variable was a rather unpleasant surprise when coming from Java to Kotlin. Two main reasons.
First, when refactoring code like
fun foo() {
val x = 123
val y = 456
val a = x + y
bar(a)
}
fun bar(a: Int) {
if (a < 0) {
val x = abs(a)
// ...
}
}
if I want to move the if (a < 0)
part from bar
to foo
, I can just copy-paste it. When I see that x
is already defined in bar
, I start thinking: what now? Are these two completely different things that accidentally happened to have the same name? Or should I reuse the same variable? If so, should I reassign a new value to it or just keep using the same one? Of course, the code above is simply made up, but it’s very often the case in real code, when local variables often have simple short names like name
, or value
, or sum
.
Second, readability. Name shadowing hurts readability a lot. I have nothing about Rust, maybe things are very different there, but with Java… really. I often have to deal with legacy code. And I mean really legacy, like single-6000-lines-God-class, or hundred-fields-half-of-which-should-be-local-vars. When I see a variable, I just have to look up its definition, and I instantly have an idea of its scope. This helps. A lot. Of course, with clean code, it’s not that much of a problem, but still, when a newbie developer writes a piece of code that is not very clean, I can understand it much faster when I don’t have to keep track of all possible variable receclarations, among other things.