为什么Kotlin允许在方法内部使用与参数同名的变量声明? [英] Why does Kotlin allow variable declarations with the same name as a parameter inside a method?

查看:67
本文介绍了为什么Kotlin允许在方法内部使用与参数同名的变量声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么Kotlin允许在方法内部使用与参数同名的变量声明?然后,还有什么方法可以访问"hidden"参数?

Why does Kotlin allow variable declarations with the same name as a parameter inside a method? Then also, is there any way to access the 'hidden' parameter?

例如:

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

推荐答案

这称为 shadowing ,它对于将代码与系统其他部分解耦很有用.可能是因为名称绑定到当前作用域.

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.

考虑一下:

您从其他人继承了一个类 Foo ,比如说一个API.在您的代码中,引入了一个变量 bar . Foo 的作者还更新了他的代码,还添加了一个变量 bar .如果没有本地范围,则会发生冲突.

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.

顺便说一下,这在包括Java在内的其他JVM基本语言中也是可能的,并且通常在构造函数或设置方法中使用:

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不仅适用于参数,其他事物也可能受到阴影:字段,方法甚至类.

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

大多数IDE都会警告您有关阴影的信息,因为它可能会造成混淆.

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

推荐使用我们自己的代码:

尝试避免阴影的原因有两个:

try to avoid shadowing for two reasons:

  • 您的代码变得难以阅读,因为两个不同的事物具有相同的名称,这会导致混乱.
  • 一旦被遮盖,您将无法再访问范围内的原始变量.

这篇关于为什么Kotlin允许在方法内部使用与参数同名的变量声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆