Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin引用函数中的全局变量_Kotlin - Fatal编程技术网

Kotlin引用函数中的全局变量

Kotlin引用函数中的全局变量,kotlin,Kotlin,这是我的密码 var offset=0 //Global offset fun foo(){ bar(offset) } fun bar(offset:Int){//Function argument offset ....... ....... ....... if(baz()){ ....... ....... offset+=10 // I want to update the global offs

这是我的密码

var offset=0 //Global offset
fun foo(){
    bar(offset)
}

fun bar(offset:Int){//Function argument offset
    .......
    .......
    .......
    if(baz()){
        .......
        .......
        offset+=10 // I want to update the global offset, but function argument offset is reffered here
        bar(offset)
    }
}

fun baz():Boolean{
    .......
    .......
}
如何在功能栏中引用全局变量“offset”(offset:Int)?
在Kotlin中不可能吗?

在本例中,您可以通过在文件级变量前面加上程序包名称来引用该变量:

package x

var offset = 0 // Global offset

fun bar(offset: Int) { // Function argument offset
    x.offset += 10 // Global offset
}

fun main(args: Array<String>) {
    bar(5)
    println(offset) // Global offset
}
x包
变量偏移量=0//全局偏移量
趣味条(offset:Int){//函数参数offset
x、 偏移量+=10//全局偏移量
}
趣味主线(args:Array){
酒吧(5)
println(offset)//全局偏移
}

在kotlin中,函数参数是不可变的(是val,不是var!),因此不能更新bar函数中的偏移量参数

最后,如果将这些代码放入类中,则可以通过“this”关键字访问与函数参数同名的类中的全局变量,如下所示:

class myClass{
    var offset=0 //Global offset
    fun foo(){
        bar(offset)
    }

    fun bar(offset:Int){//Function argument offset
        .......
        if(baz()){
            .......
            this.offset+=10 // I want to update the global offset, but function argument offset is reffered here
            .......
        }
    }

    fun baz():Boolean{
        .......
    }
}