Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
753 views
in Technique[技术] by (71.8m points)

pass value by reference in kotlin

I want to pass a value to a function so when I change the value outside that function I could see it updated in my function as well. I know that when I pass Boxed types like Int, Boolean etc they passed by value. But looks like classes are passed by value as well:

data class TestClass(var b:Boolean)
fun printBooleanIn1sec(b: TestClass) {
    Thread.sleep(1000L)
    println(b.b)
}
fun main(args: Array<String>) {
    var testClass = TestClass(false)
    printBooleanIn1sec(testClass)
    testClass.b = true
}

// prints "false"

Is there a way to pass something by reference but not by value in Kotlin if I need it?

question from:https://stackoverflow.com/questions/66050430/pass-value-by-reference-in-kotlin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Class instances are always passed by value of the reference. So the reference used in the function is pointing to the same thing as the reference passed to it, but you never have direct access to pointers in Kotlin/Java. It's important to make this distinction because "pass by reference" would mean that the function could end up looking at a different object if the higher code on the stack changed what its variable was pointing at.

The reason your code prints false is that the Thread you're sleeping is the same one that called your function, and printBooleanIn1sec() returns before testClass.b = true is reached. To illustrate the situation you wanted, you would need to spin up a new thread that sleeps and then prints the value, like:

fun printBooleanIn1sec(b: TestClass) {
    thread {
        Thread.sleep(1000L)
        println(b.b)
    }
}

Primitives are abstracted away in Kotlin, so you don't have to think of them differently than a class. But like any other immutable class, you can't change their value at all when you pass them into a function. If you want to "see" changes in the function that occur elsewhere, you'll have to wrap them in classes that hold a var property for them.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...