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

后端 未结 3 1272
忘了有多久
忘了有多久 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:35

    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.

提交回复
热议问题