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

末鹿安然 提交于 2020-08-22 04:23:27

问题


Why kotlin allows to declare variable with the same name as parameter inside the method? And is there any way to access 'hidden' parameter then?

Example:

fun main(args: Array<String>) {
    val args = Any()
}

回答1:


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.



回答2:


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.




回答3:


Something also to note and if it isn't already realized or if anyone else new comes along. In kotlin you don't have access to the params if they are not prefixed with var/val until you add them as properties. So if a basic class was defined as this:

class Person(name: String, age: Int){

}

you can't use name or age until they are in scope; however it is unnecessary to shadow with exceptions of desired reasons as miensol pointed out, but for the sake of being basic.

class Person(name: String, age: Int){
     var name = name 
     var age = age
}

do these in the constructor

class Person(var name: String, private var age: Int){           
}

you also will of course then have access based on the signature you gave on the object created.



来源:https://stackoverflow.com/questions/49680040/why-kotlin-allows-to-declare-variable-with-the-same-name-as-parameter-inside-the

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!