Why kotlin allows to declare variable with the same name as parameter inside the method?

This is called shadowing and it is useful for decoupling your code from other parts of the system. It is possible because names are bound to the current scope.

Consider this:

You subclass a class Foo from someone else, let's say an API. In your code you introduce a variable bar. The author of Foo also updates his code and also adds a variable bar. Without the local scope, you would get a conflict.

By the way, this is also possible in other JVM bases languages including Java and commonly used within constructors or setters:

public TestClass(int value, String test) {
    this.value = value;
    this.test = test;
}

public void setFoo(String foo) {
    this.foo = foo;
}

Shadowing does not only apply to parameters, other things can be shadowed too: fields, methods and even classes.

Most IDEs will warn you about shadowing as it can be confusing.

Recommendation for our own code:

try to avoid shadowing for two reasons:

  • your code becomes hard to read as two different things have the same name, which leads to confusion.
  • once shadowed, you can no longer access the original variable within a scope.

Kotlin does issue a warning about name shadowing which you can suppress with:

@Suppress("NAME_SHADOWING")
val args = Any()

Allowing for such shadowing may be handy in some cases e.g. throwing a custom exception after parameter validation:

fun sample(name: String?) {
    @Suppress("NAME_SHADOWING")
    val name = name ?: throw CustomArgumentRequiredException()
    println(name.length)
}

It is unfortunately not possible to access the shadowed variable.

It is also not possible to turn a warning into an error at the moment.

Tags:

Kotlin