如何在Kotlin中将全局变量与具有相同名称的本地变量区分开? [英] How do I distinguish a global variable from a local one with the same name in Kotlin?
问题描述
我正在学习Kotlin,在我的项目中我有类似以下内容
I'm learning Kotlin, and in my project I have something like the following
Utils.kt:
var weightInKilos = 100.0
//should multiply the above var
fun doSomething(multiplier: Double, weightInKilos: Double) {
weightInKilos = weightInKilos * multiplier
}
print(doSomething(4.2, weightInKilos))
这将是整个文件(它不是对象的一部分),所以我不能使用this关键字.我知道我可以重命名其中之一,但是是否可以使用某种标识符来区分这两个变量,所以代码显示为420?
This would be the entire file (it's not part of an object,) so I can't use the this keyword. I know I could just rename one of them but is there some kind of identifier I can use to distinguish the two vars so the code prints 420?
推荐答案
使用程序包名称作为标识符.如果Utils.kt
文件的封闭软件包为com.example
,则应使用com.example.weightInKilos = weightInKilos * multiplier
.
Use the package name as the identifier. If the enclosing package for Utils.kt
file is com.example
, you would use com.example.weightInKilos = weightInKilos * multiplier
.
谢谢您的Android Studio自动完成功能.
Thank you Android Studio autocomplete.
这篇关于如何在Kotlin中将全局变量与具有相同名称的本地变量区分开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!