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

后端 未结 3 1274
忘了有多久
忘了有多久 2021-02-07 16:17

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:

<         


        
3条回答
  •  后悔当初
    2021-02-07 16:33

    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.

提交回复
热议问题