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

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

    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.

提交回复
热议问题