Variables with same name


next scenario is possible:

val s: String = "blabla"

if (...){
   val s = "new string"

In this case on the second declaration compiler shows an warning that the variable name is shadowed. If i declare it just below the first declaration, then there is an error and it wont compile. But inside an closure it compiles.

I just spent several hours trying to find out why my variable had a completely different value than i expected, turns out it was declared two times, just like this.

Is this a feature of Kotlin? I dont like it.

Is there a way to make the shadowed variable name an error, not a warning?


Yes, this is a feature of Kotlin. At this time there is no possibility to turn a specific compiler warning into an error; I’ve filed an issue to make it possible.