Kotlin always passes by value. But if you "store a...
# announcements
d
Kotlin always passes by value. But if you "store an object in a variable" you are only storing a reference, that reference will then be passed by value.
👍 1
a
still, in example above bytecode will look like
final IntRef i = new IntRef();
But if I modify code to
Copy code
fun main(args: Array<String>) {
    var i = 23
    modifyInt(i)
    i = 33
    println("Modified $i")
}

fun modifyInt(i: Int){
    println("Call after modify $i")
}
It will be just an int in the bytecode. Although,
i
is still var.
d
Yes, because the lambda captures the variable. The lambda might read/write it, which needs to be visible outside the lambda to (and vice versa, writes outside must be visible inside).
You are not passing anything to the lambda, so the question of "pass by value" vs. "pass by reference" is not applicable. The lambda captures the variable, i.e. it's the same variable.
Kotlin has to emulate that on the JVM using the
IntRef
class.
g
Beware that the IntRef is not a volatile var, so it is not a reliable way to communicate changes between threads. The original example used a thread, but maybe that was just to show the issue.