Kotlin 从函数引用全局变量

WOL*_*F.L 6 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 offset, but function argument offset is reffered here
        bar(offset)
    }
}

fun baz():Boolean{
    .......
    .......
}
Run Code Online (Sandbox Code Playgroud)

如何在函数 bar(offset:Int) 中引用全局变量“offset”?在 Kotlin 中不可能吗?

zsm*_*b13 6

在这种情况下,您可以通过在包名称前面加上前缀来引用文件级变量:

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
}
Run Code Online (Sandbox Code Playgroud)


Ali*_*deh 1

在 kotlin 中,函数参数是不可变的(是 val,不是 var!),因此,您无法更新 bar 函数内的 offset 参数。

最后,如果将这些代码放在一个类中,那么您可以通过“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{
        .......
    }
}
Run Code Online (Sandbox Code Playgroud)