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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…