when a Kotllin class has a (non-primitive) propert...
# getting-started
y
when a Kotllin class has a (non-primitive) property, for example a
List<Foo>
, is it always passed by copy? if so, is there a way to make it hold a reference?
g
In Java and Kotlin it’s never passed by copy for objects (to be pedantic Java always pass-by-value, but in case of objects it’s always passes pointer to the object, not a copy of the object)
So on practice it means that if you pass an object, it will copy pointer on it, and as result: 1. Mutation of the object changes original object (because there is only 1 instance of it inside and outside of the function) 2. Re-assignment of original variable (so setting different pointer to it) will not change pointer passed to the function, it will continue referencing original object
And there are no operators to change it, there is no pass-by-reference in Java and in Kotlin (even in Native it represented as a wrapper on top of pointer, not as real passing by reference)
y
I see. that’s quite helpful, thanks.
g
This what I mean by wrapper: https://kotlinlang.org/api/latest/jvm/stdlib/kotlinx.cinterop/-c-pointer/ This approach is used on JVM if one wants to pass reference, so you pass object which wraps reference to another object and this reference can be mutated, so it emulates pass-by-reference
👍 1
But in general any mutation of the state is not encouraged in Kotlin, so you usually do not see this pattern in Kotlin or modern Java
👍 1
e
Kotlin/JVM uses kotlin.jvm.internal.Ref under the covers to emulate pass-by-reference when necessary, such as in
Copy code
fun counter(): () -> Int {
    var x: Int = 0
    return { x++ }
}

val f = counter()
check(f() == 0)
check(f() == 1)
// etc.
👍 1